From 3c6deab626648e47de752c33dac5d06af83e3ee3 Mon Sep 17 00:00:00 2001 From: Alex | Interchain Labs Date: Thu, 3 Apr 2025 10:42:20 -0400 Subject: [PATCH] chore: run `modernize` (#24356) --- baseapp/abci_test.go | 22 +-- baseapp/abci_utils_test.go | 2 +- baseapp/baseapp.go | 2 +- baseapp/baseapp_test.go | 8 +- baseapp/grpcrouter.go | 10 +- baseapp/grpcrouter_helpers.go | 2 +- baseapp/grpcrouter_test.go | 4 +- baseapp/grpcserver.go | 4 +- baseapp/internal/protocompat/protocompat.go | 4 +- baseapp/msg_service_router.go | 14 +- baseapp/params_legacy.go | 8 +- baseapp/recovery.go | 12 +- baseapp/recovery_test.go | 2 +- baseapp/regression_test.go | 2 +- baseapp/streaming.go | 2 +- baseapp/streaming_test.go | 10 +- client/context.go | 2 +- client/grpc_query.go | 2 +- client/keys/output_test.go | 2 +- client/tx/tx_test.go | 2 +- codec/amino.go | 44 ++--- codec/amino_codec.go | 4 +- codec/codec.go | 4 +- codec/codec_common_test.go | 2 +- codec/proto_codec.go | 12 +- codec/proto_codec_test.go | 2 +- codec/types/any_test.go | 75 ++++++++ codec/types/compat.go | 2 +- codec/types/interface_registry.go | 18 +- crypto/keys/bcrypt/base64.go | 2 +- crypto/keys/bcrypt/bcrypt.go | 9 +- crypto/keys/ed25519/ed25519_test.go | 8 +- crypto/keys/multisig/multisig.go | 8 +- crypto/keys/multisig/multisig_test.go | 10 +- .../internal/secp256k1/secp256_test.go | 6 +- crypto/keys/secp256k1/secp256k1_nocgo_test.go | 2 +- crypto/keys/secp256k1/secp256k1_test.go | 10 +- crypto/ledger/encode_test.go | 2 +- crypto/types/compact_bit_array.go | 6 +- crypto/types/compact_bit_array_test.go | 8 +- crypto/types/multisig/multisignature.go | 2 +- internal/conv/string_test.go | 4 +- runtime/services/autocli.go | 8 +- server/config/config_test.go | 4 +- server/config/toml.go | 2 +- .../grpc/gogoreflection/serverreflection.go | 2 +- server/log/cmt_logger.go | 2 +- server/mock/app.go | 4 +- server/start.go | 8 +- server/types/app.go | 2 +- server/util.go | 6 +- server/util_test.go | 4 +- simsx/delivery.go | 2 +- simsx/slices.go | 2 +- telemetry/metrics_test.go | 8 +- testutil/cli/tx.go | 4 +- testutil/compare.go | 2 +- testutil/mock/types_handler.go | 4 +- testutil/network/network.go | 14 +- testutil/network/util.go | 4 +- testutil/sims/address_helpers.go | 2 +- testutil/sims/app_helpers.go | 14 +- testutil/sims/simulation_helpers.go | 2 +- testutil/sims/state_helpers.go | 2 +- types/address.go | 6 +- types/address/hash_test.go | 3 +- types/address_race_test.go | 2 +- types/address_test.go | 8 +- types/coin.go | 2 +- types/coin_benchmark_test.go | 22 +-- types/context.go | 4 +- types/dec_coin.go | 2 +- types/events_test.go | 2 +- types/handler.go | 4 +- types/mempool/mempool_test.go | 2 +- types/mempool/priority_nonce_test.go | 8 +- types/module/configurator.go | 2 +- types/module/module.go | 6 +- types/module/module_int_test.go | 4 +- types/module/simulation.go | 2 +- types/msgservice/msg_service.go | 2 +- types/msgservice/validate.go | 2 +- types/query/filtered_pagination_test.go | 12 +- types/query/fuzz_test.go | 4 +- types/query/pagination_test.go | 6 +- types/simulation/types.go | 2 +- types/tx/ext.go | 2 +- types/tx/msgs.go | 2 +- types/utils.go | 2 +- types/utils_test.go | 3 +- version/version.go | 4 +- x/auth/ante/ante_test.go | 6 +- x/auth/ante/sigverify.go | 2 +- x/auth/ante/sigverify_test.go | 2 +- x/auth/ante/testutil_test.go | 2 +- x/auth/keeper/deterministic_test.go | 8 +- x/auth/migrations/legacytx/amino_signing.go | 2 +- x/auth/migrations/legacytx/stdsign.go | 4 +- x/auth/migrations/legacytx/stdtx_builder.go | 2 +- x/auth/tx/encode_decode_test.go | 7 +- x/auth/types/params.go | 10 +- x/authz/client/cli/tx.go | 2 +- x/authz/simulation/genesis.go | 2 +- x/bank/bench_test.go | 4 +- x/bank/keeper/grpc_query_test.go | 4 +- x/bank/keeper/keeper_test.go | 2 +- x/bank/migrations/v2/json_test.go | 2 +- x/bank/migrations/v3/store_test.go | 5 +- x/bank/migrations/v4/store_test.go | 2 +- x/bank/simulation/operations.go | 4 +- x/bank/types/balance_test.go | 6 +- x/bank/types/params.go | 2 +- x/bank/types/params_legacy.go | 4 +- x/bank/types/send_authorization.go | 2 +- x/consensus/exported/exported.go | 2 +- x/crisis/exported/exported.go | 2 +- x/crisis/migrations/v2/migrate_test.go | 2 +- x/crisis/types/legacy_params.go | 2 +- x/distribution/migrations/v3/json_test.go | 2 +- x/distribution/types/params.go | 4 +- x/distribution/types/params_internal_test.go | 2 +- x/epochs/keeper/genesis_test.go | 2 +- x/epochs/simulation/genesis.go | 2 +- x/epochs/types/hooks_test.go | 4 +- x/gov/abci_test.go | 2 +- x/gov/client/cli/prompt.go | 2 +- x/gov/exported/exported.go | 2 +- x/gov/keeper/deposit_test.go | 2 +- x/gov/keeper/grpc_query_test.go | 8 +- x/gov/migrations/v2/json_test.go | 2 +- x/gov/migrations/v3/json_test.go | 2 +- x/gov/migrations/v4/json_test.go | 2 +- x/gov/migrations/v4/store_test.go | 2 +- x/gov/simulation/msg_factory.go | 2 +- x/gov/simulation/operations.go | 2 +- x/gov/simulation/operations_test.go | 4 +- x/gov/types/expected_keepers.go | 4 +- x/gov/types/v1/params_legacy.go | 6 +- x/group/client/cli/tx_test.go | 4 +- x/group/internal/orm/auto_uint64.go | 2 +- x/group/internal/orm/example_test.go | 16 +- x/group/internal/orm/genesis.go | 2 +- x/group/internal/orm/index.go | 32 ++-- x/group/internal/orm/index_test.go | 20 +-- x/group/internal/orm/indexer.go | 38 ++-- x/group/internal/orm/indexer_test.go | 168 +++++++++--------- x/group/internal/orm/iterator.go | 2 +- x/group/internal/orm/iterator_test.go | 4 +- x/group/internal/orm/key_codec.go | 6 +- x/group/internal/orm/orm_scenario_test.go | 2 +- x/group/internal/orm/primary_key.go | 4 +- x/group/internal/orm/table.go | 4 +- x/group/internal/orm/types.go | 10 +- x/group/internal/orm/types_test.go | 2 +- x/group/keeper/keeper.go | 36 ++-- x/group/keeper/msg_server_test.go | 4 +- x/group/simulation/genesis.go | 10 +- x/group/simulation/msg_factory.go | 4 +- x/group/simulation/operations.go | 4 +- x/group/types.go | 20 +-- x/mint/types/params.go | 12 +- x/params/keeper/keeper_test.go | 10 +- x/params/simulation/operations.go | 2 +- x/params/types/common_test.go | 8 +- x/params/types/deref_test.go | 2 +- x/params/types/paramset.go | 6 +- x/params/types/subspace.go | 17 +- x/protocolpool/keeper/keeper_test.go | 2 +- x/simulation/log.go | 2 +- x/simulation/operation.go | 2 +- x/simulation/simulate.go | 6 +- x/simulation/transition_matrix.go | 12 +- x/simulation/util.go | 2 +- x/slashing/types/expected_keepers.go | 2 +- x/slashing/types/params.go | 10 +- x/staking/bench_test.go | 4 +- x/staking/client/cli/tx_test.go | 2 +- x/staking/genesis.go | 2 +- x/staking/keeper/delegation_test.go | 2 +- x/staking/migrations/v3/json_test.go | 2 +- x/staking/migrations/v3/store.go | 2 +- x/staking/migrations/v5/migrations_test.go | 2 +- x/staking/simulation/genesis.go | 2 +- x/staking/types/params.go | 14 +- x/staking/types/validator_test.go | 6 +- 185 files changed, 667 insertions(+), 590 deletions(-) create mode 100644 codec/types/any_test.go diff --git a/baseapp/abci_test.go b/baseapp/abci_test.go index 58c51a21a4..9ff7009ad5 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -635,10 +635,10 @@ func TestABCI_FinalizeBlock_DeliverTx(t *testing.T) { nBlocks := 3 txPerHeight := 5 - for blockN := 0; blockN < nBlocks; blockN++ { + for blockN := range nBlocks { txs := [][]byte{} - for i := 0; i < txPerHeight; i++ { + for i := range txPerHeight { counter := int64(blockN*txPerHeight + i) tx := newTxCounter(t, suite.txConfig, counter, counter) @@ -654,7 +654,7 @@ func TestABCI_FinalizeBlock_DeliverTx(t *testing.T) { }) require.NoError(t, err) - for i := 0; i < txPerHeight; i++ { + for i := range txPerHeight { counter := int64(blockN*txPerHeight + i) require.True(t, res.TxResults[i].IsOK(), fmt.Sprintf("%v", res)) @@ -762,7 +762,7 @@ func TestABCI_Query_SimulateTx(t *testing.T) { baseapptestutil.RegisterCounterServer(suite.baseApp.MsgServiceRouter(), CounterServerImplGasMeterOnly{gasConsumed}) nBlocks := 3 - for blockN := 0; blockN < nBlocks; blockN++ { + for blockN := range nBlocks { count := int64(blockN + 1) tx := newTxCounter(t, suite.txConfig, count, count) @@ -1093,7 +1093,7 @@ func TestABCI_MaxBlockGasLimits(t *testing.T) { require.NoError(t, err) // execute the transaction multiple times - for j := 0; j < tc.numDelivers; j++ { + for j := range tc.numDelivers { _, result, err := suite.baseApp.SimDeliver(suite.txConfig.TxEncoder(), tx) @@ -1594,7 +1594,7 @@ func TestABCI_PrepareProposal_ReachedMaxBytes(t *testing.T) { }) require.NoError(t, err) - for i := 0; i < 100; i++ { + for i := range 100 { tx2 := newTxCounter(t, suite.txConfig, int64(i), int64(i)) err := pool.Insert(sdk.Context{}, tx2) require.NoError(t, err) @@ -1970,7 +1970,7 @@ func TestABCI_Proposal_Reset_State_Between_Calls(t *testing.T) { // Let's pretend something happened and PrepareProposal gets called many // times, this must be safe to do. - for i := 0; i < 5; i++ { + for range 5 { resPrepareProposal, err := suite.baseApp.PrepareProposal(&reqPrepareProposal) require.NoError(t, err) require.Equal(t, 0, len(resPrepareProposal.Txs)) @@ -1984,7 +1984,7 @@ func TestABCI_Proposal_Reset_State_Between_Calls(t *testing.T) { // Let's pretend something happened and ProcessProposal gets called many // times, this must be safe to do. - for i := 0; i < 5; i++ { + for range 5 { resProcessProposal, err := suite.baseApp.ProcessProposal(&reqProcessProposal) require.NoError(t, err) require.Equal(t, abci.ResponseProcessProposal_ACCEPT, resProcessProposal.Status) @@ -2080,7 +2080,7 @@ func TestBaseApp_VoteExtensions(t *testing.T) { numVals := 12 privKeys := make([]secp256k1.PrivKey, numVals) vals := make([]sdk.ConsAddress, numVals) - for i := 0; i < numVals; i++ { + for i := range numVals { privKey := secp256k1.GenPrivKey() privKeys[i] = privKey @@ -2190,7 +2190,7 @@ func TestBaseApp_VoteExtensions(t *testing.T) { allVEs := [][]byte{} // simulate getting 10 vote extensions from 10 validators - for i := 0; i < 10; i++ { + for range 10 { ve, err := suite.baseApp.ExtendVote(context.TODO(), &abci.RequestExtendVote{Height: 1}) require.NoError(t, err) allVEs = append(allVEs, ve.VoteExtension) @@ -2375,7 +2375,7 @@ func TestOptimisticExecution(t *testing.T) { require.NoError(t, err) // run 50 blocks - for i := 0; i < 50; i++ { + for range 50 { tx := newTxCounter(t, suite.txConfig, 0, 1) txBytes, err := suite.txConfig.TxEncoder()(tx) require.NoError(t, err) diff --git a/baseapp/abci_utils_test.go b/baseapp/abci_utils_test.go index d7593e3bcc..1a8faf08d4 100644 --- a/baseapp/abci_utils_test.go +++ b/baseapp/abci_utils_test.go @@ -554,7 +554,7 @@ func (s *ABCIUtilsTestSuite) TestDefaultProposalHandler_NoOpMempoolTxSelection() for name, tc := range testCases { s.Run(name, func() { // iterate multiple times to ensure the tx selector is cleared each time - for i := 0; i < 6; i++ { + for range 6 { resp, err := handler(tc.ctx, tc.req) s.Require().NoError(err) s.Require().Len(resp.Txs, tc.expectedTxs) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 677f65cd7f..1e735d5aa5 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -698,7 +698,7 @@ func (app *BaseApp) cacheTxContext(ctx sdk.Context, txBytes []byte) (sdk.Context if msCache.TracingEnabled() { msCache = msCache.SetTracingContext( storetypes.TraceContext( - map[string]interface{}{ + map[string]any{ "txHash": fmt.Sprintf("%X", tmhash.Sum(txBytes)), }, ), diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index ac91491966..8edce7c0c6 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -143,10 +143,10 @@ func NewBaseAppSuiteWithSnapshots(t *testing.T, cfg SnapshotsConfig, opts ...fun _, _, addr := testdata.KeyTestPubAddr() txs := [][]byte{} - for txNum := 0; txNum < cfg.blockTxs; txNum++ { + for range cfg.blockTxs { var msgs []sdk.Msg - for msgNum := 0; msgNum < 100; msgNum++ { - key := []byte(fmt.Sprintf("%v", keyCounter)) + for range 100 { + key := fmt.Appendf(nil, "%v", keyCounter) value := make([]byte, 10000) _, err := r.Read(value) @@ -537,7 +537,7 @@ func TestCustomRunTxPanicHandler(t *testing.T) { }) require.NoError(t, err) - suite.baseApp.AddRunTxRecoveryHandler(func(recoveryObj interface{}) error { + suite.baseApp.AddRunTxRecoveryHandler(func(recoveryObj any) error { err, ok := recoveryObj.(error) if !ok { return nil diff --git a/baseapp/grpcrouter.go b/baseapp/grpcrouter.go index 9955ecb460..d88065cb25 100644 --- a/baseapp/grpcrouter.go +++ b/baseapp/grpcrouter.go @@ -35,7 +35,7 @@ type GRPCQueryRouter struct { // serviceData represents a gRPC service, along with its handler. type serviceData struct { serviceDesc *grpc.ServiceDesc - handler interface{} + handler any } var _ gogogrpc.Server = &GRPCQueryRouter{} @@ -67,7 +67,7 @@ func (qrt *GRPCQueryRouter) Route(path string) GRPCQueryHandler { // // This functions PANICS: // - if a protobuf service is registered twice. -func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { +func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler any) { // adds a top-level query handler based on the gRPC service name for _, method := range sd.Methods { err := qrt.registerABCIQueryHandler(sd, method, handler) @@ -86,7 +86,7 @@ func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler interf }) } -func (qrt *GRPCQueryRouter) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error { +func (qrt *GRPCQueryRouter) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler any) error { fqName := fmt.Sprintf("/%s/%s", sd.ServiceName, method.MethodName) methodHandler := method.Handler @@ -106,7 +106,7 @@ func (qrt *GRPCQueryRouter) registerABCIQueryHandler(sd *grpc.ServiceDesc, metho qrt.routes[fqName] = func(ctx sdk.Context, req *abci.RequestQuery) (*abci.ResponseQuery, error) { // call the method handler from the service description with the handler object, // a wrapped sdk.Context with proto-unmarshaled data from the ABCI request data - res, err := methodHandler(handler, ctx, func(i interface{}) error { + res, err := methodHandler(handler, ctx, func(i any) error { return qrt.cdc.Unmarshal(req.Data, i) }, nil) if err != nil { @@ -133,7 +133,7 @@ func (qrt *GRPCQueryRouter) HybridHandlerByRequestName(name string) []func(ctx c return qrt.hybridHandlers[name] } -func (qrt *GRPCQueryRouter) registerHybridHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error { +func (qrt *GRPCQueryRouter) registerHybridHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler any) error { // extract message name from method descriptor inputName, err := protocompat.RequestFullNameFromMethodDesc(sd, method) if err != nil { diff --git a/baseapp/grpcrouter_helpers.go b/baseapp/grpcrouter_helpers.go index 9f737e0e06..877c9d6654 100644 --- a/baseapp/grpcrouter_helpers.go +++ b/baseapp/grpcrouter_helpers.go @@ -35,7 +35,7 @@ func NewQueryServerTestHelper(ctx sdk.Context, interfaceRegistry types.Interface } // Invoke implements the grpc ClientConn.Invoke method -func (q *QueryServiceTestHelper) Invoke(_ gocontext.Context, method string, args, reply interface{}, _ ...grpc.CallOption) error { +func (q *QueryServiceTestHelper) Invoke(_ gocontext.Context, method string, args, reply any, _ ...grpc.CallOption) error { querier := q.Route(method) if querier == nil { return fmt.Errorf("handler not found for %s", method) diff --git a/baseapp/grpcrouter_test.go b/baseapp/grpcrouter_test.go index a8ba3892b2..5e11fc3a3e 100644 --- a/baseapp/grpcrouter_test.go +++ b/baseapp/grpcrouter_test.go @@ -182,13 +182,13 @@ func testQueryDataRacesSameHandler(t *testing.T, makeClientConn func(*baseapp.GR n := 1000 ready := make(chan bool, n) go func() { - for i := 0; i < n; i++ { + for range n { <-ready } close(greenlight) }() - for i := 0; i < n; i++ { + for range n { wg.Add(1) go func() { defer wg.Done() diff --git a/baseapp/grpcserver.go b/baseapp/grpcserver.go index 4c98c5bae4..159cf144f0 100644 --- a/baseapp/grpcserver.go +++ b/baseapp/grpcserver.go @@ -38,7 +38,7 @@ func (app *BaseApp) RegisterGRPCServer(server gogogrpc.Server) { func (app *BaseApp) RegisterGRPCServerWithSkipCheckHeader(server gogogrpc.Server, skipCheckHeader bool) { // Define an interceptor for all gRPC queries: this interceptor will create // a new sdk.Context, and pass it into the query handler. - interceptor := func(grpcCtx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + interceptor := func(grpcCtx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { // If there's some metadata in the context, retrieve it. md, ok := metadata.FromIncomingContext(grpcCtx) if !ok { @@ -106,7 +106,7 @@ func (app *BaseApp) RegisterGRPCServerWithSkipCheckHeader(server gogogrpc.Server methodHandler := method.Handler newMethods[i] = grpc.MethodDesc{ MethodName: method.MethodName, - Handler: func(srv interface{}, ctx context.Context, dec func(interface{}) error, _ grpc.UnaryServerInterceptor) (interface{}, error) { + Handler: func(srv any, ctx context.Context, dec func(any) error, _ grpc.UnaryServerInterceptor) (any, error) { return methodHandler(srv, ctx, dec, grpcmiddleware.ChainUnaryServer( grpcrecovery.UnaryServerInterceptor(), interceptor, diff --git a/baseapp/internal/protocompat/protocompat.go b/baseapp/internal/protocompat/protocompat.go index 6b8cdc0818..ec296b9147 100644 --- a/baseapp/internal/protocompat/protocompat.go +++ b/baseapp/internal/protocompat/protocompat.go @@ -24,7 +24,7 @@ var ( type Handler = func(ctx context.Context, request, response protoiface.MessageV1) error -func MakeHybridHandler(cdc codec.BinaryCodec, sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) (Handler, error) { +func MakeHybridHandler(cdc codec.BinaryCodec, sd *grpc.ServiceDesc, method grpc.MethodDesc, handler any) (Handler, error) { methodFullName := protoreflect.FullName(fmt.Sprintf("%s.%s", sd.ServiceName, method.MethodName)) desc, err := gogoproto.HybridResolver.FindDescriptorByName(methodFullName) if err != nil { @@ -193,7 +193,7 @@ func makeGogoHybridHandler(prefMethod protoreflect.MethodDescriptor, cdc codec.B // the type. Since the decoder function is passed in by the concrete implementer the expected // message where bytes are unmarshaled to, we can use that to determine the type. func isProtov2(md grpc.MethodDesc) (isV2Type bool, err error) { - pullRequestType := func(msg interface{}) error { + pullRequestType := func(msg any) error { typ := reflect.TypeOf(msg) switch { case typ.Implements(protov2Type): diff --git a/baseapp/msg_service_router.go b/baseapp/msg_service_router.go index 126e0f65e5..d6ecbadc9e 100644 --- a/baseapp/msg_service_router.go +++ b/baseapp/msg_service_router.go @@ -68,7 +68,7 @@ func (msr *MsgServiceRouter) HandlerByTypeURL(typeURL string) MsgServiceHandler // - if it is called before the service `Msg`s have been registered using // RegisterInterfaces, // - or if a service is being registered twice. -func (msr *MsgServiceRouter) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { +func (msr *MsgServiceRouter) RegisterService(sd *grpc.ServiceDesc, handler any) { // Adds a top-level query handler based on the gRPC service name. for _, method := range sd.Methods { err := msr.registerMsgServiceHandler(sd, method, handler) @@ -86,7 +86,7 @@ func (msr *MsgServiceRouter) HybridHandlerByMsgName(msgName string) func(ctx con return msr.hybridHandlers[msgName] } -func (msr *MsgServiceRouter) registerHybridHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error { +func (msr *MsgServiceRouter) registerHybridHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler any) error { inputName, err := protocompat.RequestFullNameFromMethodDesc(sd, method) if err != nil { return err @@ -117,7 +117,7 @@ func (msr *MsgServiceRouter) registerHybridHandler(sd *grpc.ServiceDesc, method return nil } -func (msr *MsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) error { +func (msr *MsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler any) error { fqMethod := fmt.Sprintf("/%s/%s", sd.ServiceName, method.MethodName) methodHandler := method.Handler @@ -126,7 +126,7 @@ func (msr *MsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, met // NOTE: This is how we pull the concrete request type for each handler for registering in the InterfaceRegistry. // This approach is maybe a bit hacky, but less hacky than reflecting on the handler object itself. // We use a no-op interceptor to avoid actually calling into the handler itself. - _, _ = methodHandler(nil, context.Background(), func(i interface{}) error { + _, _ = methodHandler(nil, context.Background(), func(i any) error { msg, ok := i.(sdk.Msg) if !ok { // We panic here because there is no other alternative and the app cannot be initialized correctly @@ -170,7 +170,7 @@ func (msr *MsgServiceRouter) registerMsgServiceHandler(sd *grpc.ServiceDesc, met msr.routes[requestTypeName] = func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) - interceptor := func(goCtx context.Context, _ interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + interceptor := func(goCtx context.Context, _ any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { goCtx = context.WithValue(goCtx, sdk.SdkContextKey, ctx) return handler(goCtx, msg) } @@ -215,7 +215,7 @@ func (msr *MsgServiceRouter) SetInterfaceRegistry(interfaceRegistry codectypes.I msr.interfaceRegistry = interfaceRegistry } -func noopDecoder(_ interface{}) error { return nil } -func noopInterceptor(_ context.Context, _ interface{}, _ *grpc.UnaryServerInfo, _ grpc.UnaryHandler) (interface{}, error) { +func noopDecoder(_ any) error { return nil } +func noopInterceptor(_ context.Context, _ any, _ *grpc.UnaryServerInfo, _ grpc.UnaryHandler) (any, error) { return nil, nil } diff --git a/baseapp/params_legacy.go b/baseapp/params_legacy.go index 13fd34add7..c367194605 100644 --- a/baseapp/params_legacy.go +++ b/baseapp/params_legacy.go @@ -52,11 +52,11 @@ var ( ) type LegacyParamStore interface { - Get(ctx sdk.Context, key []byte, ptr interface{}) + Get(ctx sdk.Context, key []byte, ptr any) Has(ctx sdk.Context, key []byte) bool } -func ValidateBlockParams(i interface{}) error { +func ValidateBlockParams(i any) error { v, ok := i.(cmtproto.BlockParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -73,7 +73,7 @@ func ValidateBlockParams(i interface{}) error { return nil } -func ValidateEvidenceParams(i interface{}) error { +func ValidateEvidenceParams(i any) error { v, ok := i.(cmtproto.EvidenceParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -94,7 +94,7 @@ func ValidateEvidenceParams(i interface{}) error { return nil } -func ValidateValidatorParams(i interface{}) error { +func ValidateValidatorParams(i any) error { v, ok := i.(cmtproto.ValidatorParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/baseapp/recovery.go b/baseapp/recovery.go index ca6cfca062..30d43e1e6a 100644 --- a/baseapp/recovery.go +++ b/baseapp/recovery.go @@ -14,16 +14,16 @@ import ( // RecoveryHandler handles recovery() object. // Return a non-nil error if recoveryObj was processed. // Return nil if recoveryObj was not processed. -type RecoveryHandler func(recoveryObj interface{}) error +type RecoveryHandler func(recoveryObj any) error // recoveryMiddleware is wrapper for RecoveryHandler to create chained recovery handling. // returns (recoveryMiddleware, nil) if recoveryObj was not processed and should be passed to the next middleware in chain. // returns (nil, error) if recoveryObj was processed and middleware chain processing should be stopped. -type recoveryMiddleware func(recoveryObj interface{}) (recoveryMiddleware, error) +type recoveryMiddleware func(recoveryObj any) (recoveryMiddleware, error) // processRecovery processes recoveryMiddleware chain for recovery() object. // Chain processing stops on non-nil error or when chain is processed. -func processRecovery(recoveryObj interface{}, middleware recoveryMiddleware) error { +func processRecovery(recoveryObj any, middleware recoveryMiddleware) error { if middleware == nil { return nil } @@ -38,7 +38,7 @@ func processRecovery(recoveryObj interface{}, middleware recoveryMiddleware) err // newRecoveryMiddleware creates a RecoveryHandler middleware. func newRecoveryMiddleware(handler RecoveryHandler, next recoveryMiddleware) recoveryMiddleware { - return func(recoveryObj interface{}) (recoveryMiddleware, error) { + return func(recoveryObj any) (recoveryMiddleware, error) { if err := handler(recoveryObj); err != nil { return nil, err } @@ -49,7 +49,7 @@ func newRecoveryMiddleware(handler RecoveryHandler, next recoveryMiddleware) rec // newOutOfGasRecoveryMiddleware creates a standard OutOfGas recovery middleware for app.runTx method. func newOutOfGasRecoveryMiddleware(gasWanted uint64, ctx sdk.Context, next recoveryMiddleware) recoveryMiddleware { - handler := func(recoveryObj interface{}) error { + handler := func(recoveryObj any) error { err, ok := recoveryObj.(storetypes.ErrorOutOfGas) if !ok { return nil @@ -68,7 +68,7 @@ func newOutOfGasRecoveryMiddleware(gasWanted uint64, ctx sdk.Context, next recov // newDefaultRecoveryMiddleware creates a default (last in chain) recovery middleware for app.runTx method. func newDefaultRecoveryMiddleware() recoveryMiddleware { - handler := func(recoveryObj interface{}) error { + handler := func(recoveryObj any) error { return errorsmod.Wrap( sdkerrors.ErrPanic, fmt.Sprintf( "recovered: %v\nstack:\n%v", recoveryObj, string(debug.Stack()), diff --git a/baseapp/recovery_test.go b/baseapp/recovery_test.go index b75892c638..238b389c74 100644 --- a/baseapp/recovery_test.go +++ b/baseapp/recovery_test.go @@ -14,7 +14,7 @@ func TestRecoveryChain(t *testing.T) { } createHandler := func(id int, handle bool) RecoveryHandler { - return func(_ interface{}) error { + return func(_ any) error { if handle { return createError(id) } diff --git a/baseapp/regression_test.go b/baseapp/regression_test.go index c93d732299..6e8265718d 100644 --- a/baseapp/regression_test.go +++ b/baseapp/regression_test.go @@ -18,7 +18,7 @@ func TestNilCmsCheckBeforeSeal(t *testing.T) { // 1. Invoking app.Init with a nil cms MUST not seal the app // and should return an error firstly, which can later be reversed. - for i := 0; i < 10; i++ { // N times, the app shouldn't be sealed. + for range 10 { // N times, the app shouldn't be sealed. err := app.Init() require.Error(t, err) require.Contains(t, err.Error(), "commit multi-store must not be nil") diff --git a/baseapp/streaming.go b/baseapp/streaming.go index c548b2a1d2..fcba3c2a20 100644 --- a/baseapp/streaming.go +++ b/baseapp/streaming.go @@ -49,7 +49,7 @@ func (app *BaseApp) RegisterStreamingServices(appOpts servertypes.AppOptions, ke func (app *BaseApp) registerStreamingPlugin( appOpts servertypes.AppOptions, keys map[string]*storetypes.KVStoreKey, - streamingPlugin interface{}, + streamingPlugin any, ) error { v, ok := streamingPlugin.(storetypes.ABCIListener) if !ok { diff --git a/baseapp/streaming_test.go b/baseapp/streaming_test.go index 50011eacea..ed3637dbc9 100644 --- a/baseapp/streaming_test.go +++ b/baseapp/streaming_test.go @@ -64,7 +64,7 @@ func TestABCI_MultiListener_StateChanges(t *testing.T) { nBlocks := 3 txPerHeight := 5 - for blockN := 0; blockN < nBlocks; blockN++ { + for blockN := range nBlocks { txs := [][]byte{} var expectedChangeSet []*storetypes.StoreKVPair @@ -73,15 +73,15 @@ func TestABCI_MultiListener_StateChanges(t *testing.T) { _, err := suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: int64(blockN) + 1, Txs: txs}) require.NoError(t, err) - for i := 0; i < txPerHeight; i++ { + for i := range txPerHeight { counter := int64(blockN*txPerHeight + i) tx := newTxCounter(t, suite.txConfig, counter, counter) txBytes, err := suite.txConfig.TxEncoder()(tx) require.NoError(t, err) - sKey := []byte(fmt.Sprintf("distKey%d", i)) - sVal := []byte(fmt.Sprintf("distVal%d", i)) + sKey := fmt.Appendf(nil, "distKey%d", i) + sVal := fmt.Appendf(nil, "distVal%d", i) store := getFinalizeBlockStateCtx(suite.baseApp).KVStore(distKey1) store.Set(sKey, sVal) @@ -134,7 +134,7 @@ func Test_Ctx_with_StreamingManager(t *testing.T) { nBlocks := 2 - for blockN := 0; blockN < nBlocks; blockN++ { + for blockN := range nBlocks { _, err := suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: int64(blockN) + 1}) require.NoError(t, err) diff --git a/client/context.go b/client/context.go index 3c98d625c3..fba315f377 100644 --- a/client/context.go +++ b/client/context.go @@ -340,7 +340,7 @@ func (ctx Context) PrintProto(toPrint proto.Message) error { // PrintObjectLegacy is a variant of PrintProto that doesn't require a proto.Message type // and uses amino JSON encoding. // Deprecated: It will be removed in the near future! -func (ctx Context) PrintObjectLegacy(toPrint interface{}) error { +func (ctx Context) PrintObjectLegacy(toPrint any) error { out, err := ctx.LegacyAmino.MarshalJSON(toPrint) if err != nil { return err diff --git a/client/grpc_query.go b/client/grpc_query.go index 493ffe1ae9..d48f8231f3 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -29,7 +29,7 @@ var _ gogogrpc.ClientConn = Context{} var fallBackCodec = codec.NewProtoCodec(types.NewInterfaceRegistry()) // Invoke implements the grpc ClientConn.Invoke method -func (ctx Context) Invoke(grpcCtx gocontext.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { +func (ctx Context) Invoke(grpcCtx gocontext.Context, method string, req, reply any, opts ...grpc.CallOption) (err error) { // Two things can happen here: // 1. either we're broadcasting a Tx, in which call we call CometBFT's broadcast endpoint directly, // 2-1. or we are querying for state, in which case we call grpc if grpc client set. diff --git a/client/keys/output_test.go b/client/keys/output_test.go index fc8e4bf321..43bbde3e8b 100644 --- a/client/keys/output_test.go +++ b/client/keys/output_test.go @@ -18,7 +18,7 @@ import ( func generatePubKeys(n int) []types.PubKey { pks := make([]types.PubKey, n) - for i := 0; i < n; i++ { + for i := range n { pks[i] = secp256k1.GenPrivKey().PubKey() } return pks diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index 190fbf4efe..900d5ec9da 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -38,7 +38,7 @@ type mockContext struct { wantErr bool } -func (m mockContext) Invoke(_ context.Context, _ string, _, reply interface{}, _ ...grpc.CallOption) (err error) { +func (m mockContext) Invoke(_ context.Context, _ string, _, reply any, _ ...grpc.CallOption) (err error) { if m.wantErr { return fmt.Errorf("mock err") } diff --git a/codec/amino.go b/codec/amino.go index f17dbcc4a4..ea5ab67abf 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -37,7 +37,7 @@ func RegisterEvidences(cdc *LegacyAmino) { // MarshalJSONIndent provides a utility for indented JSON encoding of an object // via an Amino codec. It returns an error if it cannot serialize or indent as // JSON. -func MarshalJSONIndent(cdc *LegacyAmino, obj interface{}) ([]byte, error) { +func MarshalJSONIndent(cdc *LegacyAmino, obj any) ([]byte, error) { bz, err := cdc.MarshalJSON(obj) if err != nil { return nil, err @@ -51,7 +51,7 @@ func MarshalJSONIndent(cdc *LegacyAmino, obj interface{}) ([]byte, error) { } // MustMarshalJSONIndent executes MarshalJSONIndent except it panics upon failure. -func MustMarshalJSONIndent(cdc *LegacyAmino, obj interface{}) []byte { +func MustMarshalJSONIndent(cdc *LegacyAmino, obj any) []byte { bz, err := MarshalJSONIndent(cdc, obj) if err != nil { panic(fmt.Sprintf("failed to marshal JSON: %s", err)) @@ -60,23 +60,23 @@ func MustMarshalJSONIndent(cdc *LegacyAmino, obj interface{}) []byte { return bz } -func (cdc *LegacyAmino) marshalAnys(o interface{}) error { +func (cdc *LegacyAmino) marshalAnys(o any) error { return types.UnpackInterfaces(o, types.AminoPacker{Cdc: cdc.Amino}) } -func (cdc *LegacyAmino) unmarshalAnys(o interface{}) error { +func (cdc *LegacyAmino) unmarshalAnys(o any) error { return types.UnpackInterfaces(o, types.AminoUnpacker{Cdc: cdc.Amino}) } -func (cdc *LegacyAmino) jsonMarshalAnys(o interface{}) error { +func (cdc *LegacyAmino) jsonMarshalAnys(o any) error { return types.UnpackInterfaces(o, types.AminoJSONPacker{Cdc: cdc.Amino}) } -func (cdc *LegacyAmino) jsonUnmarshalAnys(o interface{}) error { +func (cdc *LegacyAmino) jsonUnmarshalAnys(o any) error { return types.UnpackInterfaces(o, types.AminoJSONUnpacker{Cdc: cdc.Amino}) } -func (cdc *LegacyAmino) Marshal(o interface{}) ([]byte, error) { +func (cdc *LegacyAmino) Marshal(o any) ([]byte, error) { err := cdc.marshalAnys(o) if err != nil { return nil, err @@ -84,7 +84,7 @@ func (cdc *LegacyAmino) Marshal(o interface{}) ([]byte, error) { return cdc.Amino.MarshalBinaryBare(o) } -func (cdc *LegacyAmino) MustMarshal(o interface{}) []byte { +func (cdc *LegacyAmino) MustMarshal(o any) []byte { bz, err := cdc.Marshal(o) if err != nil { panic(err) @@ -92,7 +92,7 @@ func (cdc *LegacyAmino) MustMarshal(o interface{}) []byte { return bz } -func (cdc *LegacyAmino) MarshalLengthPrefixed(o interface{}) ([]byte, error) { +func (cdc *LegacyAmino) MarshalLengthPrefixed(o any) ([]byte, error) { err := cdc.marshalAnys(o) if err != nil { return nil, err @@ -100,7 +100,7 @@ func (cdc *LegacyAmino) MarshalLengthPrefixed(o interface{}) ([]byte, error) { return cdc.Amino.MarshalBinaryLengthPrefixed(o) } -func (cdc *LegacyAmino) MustMarshalLengthPrefixed(o interface{}) []byte { +func (cdc *LegacyAmino) MustMarshalLengthPrefixed(o any) []byte { bz, err := cdc.MarshalLengthPrefixed(o) if err != nil { panic(err) @@ -108,7 +108,7 @@ func (cdc *LegacyAmino) MustMarshalLengthPrefixed(o interface{}) []byte { return bz } -func (cdc *LegacyAmino) Unmarshal(bz []byte, ptr interface{}) error { +func (cdc *LegacyAmino) Unmarshal(bz []byte, ptr any) error { err := cdc.Amino.UnmarshalBinaryBare(bz, ptr) if err != nil { return err @@ -116,14 +116,14 @@ func (cdc *LegacyAmino) Unmarshal(bz []byte, ptr interface{}) error { return cdc.unmarshalAnys(ptr) } -func (cdc *LegacyAmino) MustUnmarshal(bz []byte, ptr interface{}) { +func (cdc *LegacyAmino) MustUnmarshal(bz []byte, ptr any) { err := cdc.Unmarshal(bz, ptr) if err != nil { panic(err) } } -func (cdc *LegacyAmino) UnmarshalLengthPrefixed(bz []byte, ptr interface{}) error { +func (cdc *LegacyAmino) UnmarshalLengthPrefixed(bz []byte, ptr any) error { err := cdc.Amino.UnmarshalBinaryLengthPrefixed(bz, ptr) if err != nil { return err @@ -131,7 +131,7 @@ func (cdc *LegacyAmino) UnmarshalLengthPrefixed(bz []byte, ptr interface{}) erro return cdc.unmarshalAnys(ptr) } -func (cdc *LegacyAmino) MustUnmarshalLengthPrefixed(bz []byte, ptr interface{}) { +func (cdc *LegacyAmino) MustUnmarshalLengthPrefixed(bz []byte, ptr any) { err := cdc.UnmarshalLengthPrefixed(bz, ptr) if err != nil { panic(err) @@ -139,7 +139,7 @@ func (cdc *LegacyAmino) MustUnmarshalLengthPrefixed(bz []byte, ptr interface{}) } // MarshalJSON implements codec.Codec interface -func (cdc *LegacyAmino) MarshalJSON(o interface{}) ([]byte, error) { +func (cdc *LegacyAmino) MarshalJSON(o any) ([]byte, error) { err := cdc.jsonMarshalAnys(o) if err != nil { return nil, err @@ -147,7 +147,7 @@ func (cdc *LegacyAmino) MarshalJSON(o interface{}) ([]byte, error) { return cdc.Amino.MarshalJSON(o) } -func (cdc *LegacyAmino) MustMarshalJSON(o interface{}) []byte { +func (cdc *LegacyAmino) MustMarshalJSON(o any) []byte { bz, err := cdc.MarshalJSON(o) if err != nil { panic(err) @@ -156,7 +156,7 @@ func (cdc *LegacyAmino) MustMarshalJSON(o interface{}) []byte { } // UnmarshalJSON implements codec.Codec interface -func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr interface{}) error { +func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr any) error { err := cdc.Amino.UnmarshalJSON(bz, ptr) if err != nil { return err @@ -164,26 +164,26 @@ func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr interface{}) error { return cdc.jsonUnmarshalAnys(ptr) } -func (cdc *LegacyAmino) MustUnmarshalJSON(bz []byte, ptr interface{}) { +func (cdc *LegacyAmino) MustUnmarshalJSON(bz []byte, ptr any) { err := cdc.UnmarshalJSON(bz, ptr) if err != nil { panic(err) } } -func (*LegacyAmino) UnpackAny(*types.Any, interface{}) error { +func (*LegacyAmino) UnpackAny(*types.Any, any) error { return errors.New("AminoCodec can't handle unpack protobuf Any's") } -func (cdc *LegacyAmino) RegisterInterface(ptr interface{}, iopts *amino.InterfaceOptions) { +func (cdc *LegacyAmino) RegisterInterface(ptr any, iopts *amino.InterfaceOptions) { cdc.Amino.RegisterInterface(ptr, iopts) } -func (cdc *LegacyAmino) RegisterConcrete(o interface{}, name string, copts *amino.ConcreteOptions) { +func (cdc *LegacyAmino) RegisterConcrete(o any, name string, copts *amino.ConcreteOptions) { cdc.Amino.RegisterConcrete(o, name, copts) } -func (cdc *LegacyAmino) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) { +func (cdc *LegacyAmino) MarshalJSONIndent(o any, prefix, indent string) ([]byte, error) { err := cdc.jsonMarshalAnys(o) if err != nil { panic(err) diff --git a/codec/amino_codec.go b/codec/amino_codec.go index c4bc0bd0d1..5aceede5b2 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -104,7 +104,7 @@ func (ac *AminoCodec) MarshalInterface(i proto.Message) ([]byte, error) { // // var x MyInterface // err := cdc.UnmarshalInterface(bz, &x) -func (ac *AminoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { +func (ac *AminoCodec) UnmarshalInterface(bz []byte, ptr any) error { return ac.LegacyAmino.Unmarshal(bz, ptr) } @@ -126,6 +126,6 @@ func (ac *AminoCodec) MarshalInterfaceJSON(i proto.Message) ([]byte, error) { // // var x MyInterface // err := cdc.UnmarshalInterfaceJSON(bz, &x) -func (ac *AminoCodec) UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error { +func (ac *AminoCodec) UnmarshalInterfaceJSON(bz []byte, ptr any) error { return ac.LegacyAmino.UnmarshalJSON(bz, ptr) } diff --git a/codec/codec.go b/codec/codec.go index 6256f78a80..dc2f5e0d64 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -72,7 +72,7 @@ type ( // UnmarshalInterface is a helper method which will parse binary enoded data // into `Any` and unpack any into the `ptr`. It fails if the target interface type // is not registered in codec, or is not compatible with the serialized data - UnmarshalInterface(bz []byte, ptr interface{}) error + UnmarshalInterface(bz []byte, ptr any) error types.AnyUnpacker } @@ -88,7 +88,7 @@ type ( // UnmarshalInterfaceJSON is a helper method which will parse JSON enoded data // into `Any` and unpack any into the `ptr`. It fails if the target interface type // is not registered in codec, or is not compatible with the serialized data - UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error + UnmarshalInterfaceJSON(bz []byte, ptr any) error // UnmarshalJSON parses the data encoded with MarshalJSON method and stores the result // in the value pointed to by v. diff --git a/codec/codec_common_test.go b/codec/codec_common_test.go index cb0fba9311..ddfae18e44 100644 --- a/codec/codec_common_test.go +++ b/codec/codec_common_test.go @@ -13,7 +13,7 @@ import ( type interfaceMarshaler struct { marshal func(i proto.Message) ([]byte, error) - unmarshal func(bz []byte, ptr interface{}) error + unmarshal func(bz []byte, ptr any) error } func testInterfaceMarshaling(require *require.Assertions, cdc interfaceMarshaler, isAminoBin bool) { diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 11fa7859c1..6d22ee1d49 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -248,7 +248,7 @@ func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) { // // var x MyInterface // err := cdc.UnmarshalInterface(bz, &x) -func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { +func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr any) error { any := &types.Any{} err := pc.Unmarshal(bz, any) if err != nil { @@ -278,7 +278,7 @@ func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) // // var x MyInterface // must implement proto.Message // err := cdc.UnmarshalInterfaceJSON(&x, bz) -func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface interface{}) error { +func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface any) error { any := &types.Any{} err := pc.UnmarshalJSON(bz, any) if err != nil { @@ -290,7 +290,7 @@ func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface interface{}) error // UnpackAny implements AnyUnpacker.UnpackAny method, // it unpacks the value in any to the interface pointer passed in as // iface. -func (pc *ProtoCodec) UnpackAny(any *types.Any, iface interface{}) error { +func (pc *ProtoCodec) UnpackAny(any *types.Any, iface any) error { return pc.interfaceRegistry.UnpackAny(any, iface) } @@ -342,7 +342,7 @@ type grpcProtoCodec struct { cdc *ProtoCodec } -func (g grpcProtoCodec) Marshal(v interface{}) ([]byte, error) { +func (g grpcProtoCodec) Marshal(v any) ([]byte, error) { switch m := v.(type) { case proto.Message: protov2MarshalOpts := proto.MarshalOptions{Deterministic: true} @@ -354,7 +354,7 @@ func (g grpcProtoCodec) Marshal(v interface{}) ([]byte, error) { } } -func (g grpcProtoCodec) Unmarshal(data []byte, v interface{}) error { +func (g grpcProtoCodec) Unmarshal(data []byte, v any) error { switch m := v.(type) { case proto.Message: return proto.Unmarshal(data, m) @@ -369,7 +369,7 @@ func (g grpcProtoCodec) Name() string { return "cosmos-sdk-grpc-codec" } -func assertNotNil(i interface{}) error { +func assertNotNil(i any) error { if i == nil { return errors.New("can't marshal value") } diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 95236a472d..a7743d16c5 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -121,7 +121,7 @@ func TestProtoCodecMarshal(t *testing.T) { // Emulate grpc server implementation // https://github.com/grpc/grpc-go/blob/b1d7f56b81b7902d871111b82dec6ba45f854ede/rpc_util.go#L590 -func grpcServerEncode(c encoding.Codec, msg interface{}) ([]byte, error) { +func grpcServerEncode(c encoding.Codec, msg any) ([]byte, error) { if msg == nil { // NOTE: typed nils will not be caught by this check return nil, nil } diff --git a/codec/types/any_test.go b/codec/types/any_test.go new file mode 100644 index 0000000000..950552959b --- /dev/null +++ b/codec/types/any_test.go @@ -0,0 +1,75 @@ +package types_test + +import ( + "fmt" + "runtime" + "testing" + + "github.com/cosmos/gogoproto/proto" + + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" +) + +type errOnMarshal struct { + testdata.Dog +} + +var _ proto.Message = (*errOnMarshal)(nil) + +var errAlways = fmt.Errorf("always erroring") + +func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return nil, errAlways +} + +var eom = &errOnMarshal{} + +// Ensure that returning an error doesn't suddenly allocate and waste bytes. +// See https://github.com/cosmos/cosmos-sdk/issues/8537 +func TestNewAnyWithCustomTypeURLWithErrorNoAllocation(t *testing.T) { + // This tests continues to fail inconsistently. + // + // Example: https://github.com/cosmos/cosmos-sdk/pull/9246/checks?check_run_id=2643313958#step:6:118 + // Ref: https://github.com/cosmos/cosmos-sdk/issues/9010 + t.SkipNow() + + // make sure we're not in the middle of a GC. + runtime.GC() + + var ms1, ms2 runtime.MemStats + runtime.ReadMemStats(&ms1) + any, err := types.NewAnyWithValue(eom) + runtime.ReadMemStats(&ms2) + // Ensure that no fresh allocation was made. + if diff := ms2.HeapAlloc - ms1.HeapAlloc; diff > 0 { + t.Errorf("Unexpected allocation of %d bytes", diff) + } + if err == nil { + t.Fatal("err wasn't returned") + } + if any != nil { + t.Fatalf("Unexpectedly got a non-nil Any value: %v", any) + } +} + +var sink any + +func BenchmarkNewAnyWithCustomTypeURLWithErrorReturned(b *testing.B) { + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + any, err := types.NewAnyWithValue(eom) + if err == nil { + b.Fatal("err wasn't returned") + } + if any != nil { + b.Fatalf("Unexpectedly got a non-nil Any value: %v", any) + } + sink = any + } + if sink == nil { + b.Fatal("benchmark didn't run") + } + sink = (any)(nil) +} diff --git a/codec/types/compat.go b/codec/types/compat.go index 968060eddc..88c6e0acf3 100644 --- a/codec/types/compat.go +++ b/codec/types/compat.go @@ -19,5 +19,5 @@ type AminoJSONUnpacker = gogoany.AminoJSONUnpacker // AminoJSONPacker is an alias for github.com/cosmos/gogoproto/types/any.AminoJSONPacker. type AminoJSONPacker = gogoany.AminoJSONPacker -// ProtoUnpacker is an alias for github.com/cosmos/gogoproto/types/any.ProtoJSONPacker. +// ProtoJSONPacker is an alias for github.com/cosmos/gogoproto/types/any.ProtoJSONPacker. type ProtoJSONPacker = gogoany.ProtoJSONPacker diff --git a/codec/types/interface_registry.go b/codec/types/interface_registry.go index ffb891664d..d03e1d987f 100644 --- a/codec/types/interface_registry.go +++ b/codec/types/interface_registry.go @@ -54,14 +54,14 @@ type InterfaceRegistry interface { // // Ex: // registry.RegisterInterface("cosmos.base.v1beta1.Msg", (*sdk.Msg)(nil)) - RegisterInterface(protoName string, iface interface{}, impls ...proto.Message) + RegisterInterface(protoName string, iface any, impls ...proto.Message) // RegisterImplementations registers impls as concrete implementations of // the interface iface. // // Ex: // registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSend{}, &MsgMultiSend{}) - RegisterImplementations(iface interface{}, impls ...proto.Message) + RegisterImplementations(iface any, impls ...proto.Message) // ListAllInterfaces list the type URLs of all registered interfaces. ListAllInterfaces() []string @@ -71,7 +71,7 @@ type InterfaceRegistry interface { ListImplementations(ifaceTypeURL string) []string // EnsureRegistered ensures there is a registered interface for the given concrete type. - EnsureRegistered(iface interface{}) error + EnsureRegistered(iface any) error protodesc.Resolver @@ -169,7 +169,7 @@ func NewInterfaceRegistryWithOptions(options InterfaceRegistryOptions) (Interfac }, nil } -func (registry *interfaceRegistry) RegisterInterface(protoName string, iface interface{}, impls ...proto.Message) { +func (registry *interfaceRegistry) RegisterInterface(protoName string, iface any, impls ...proto.Message) { typ := reflect.TypeOf(iface) if typ.Elem().Kind() != reflect.Interface { panic(fmt.Errorf("%T is not an interface type", iface)) @@ -182,7 +182,7 @@ func (registry *interfaceRegistry) RegisterInterface(protoName string, iface int // EnsureRegistered ensures there is a registered interface for the given concrete type. // // Returns an error if not, and nil if so. -func (registry *interfaceRegistry) EnsureRegistered(impl interface{}) error { +func (registry *interfaceRegistry) EnsureRegistered(impl any) error { if reflect.ValueOf(impl).Kind() != reflect.Ptr { return fmt.Errorf("%T is not a pointer", impl) } @@ -199,7 +199,7 @@ func (registry *interfaceRegistry) EnsureRegistered(impl interface{}) error { // // This function PANICs if different concrete types are registered under the // same typeURL. -func (registry *interfaceRegistry) RegisterImplementations(iface interface{}, impls ...proto.Message) { +func (registry *interfaceRegistry) RegisterImplementations(iface any, impls ...proto.Message) { for _, impl := range impls { typeURL := MsgTypeURL(impl) registry.registerImpl(iface, typeURL, impl) @@ -211,7 +211,7 @@ func (registry *interfaceRegistry) RegisterImplementations(iface interface{}, im // // This function PANICs if different concrete types are registered under the // same typeURL. -func (registry *interfaceRegistry) RegisterCustomTypeURL(iface interface{}, typeURL string, impl proto.Message) { +func (registry *interfaceRegistry) RegisterCustomTypeURL(iface any, typeURL string, impl proto.Message) { registry.registerImpl(iface, typeURL, impl) } @@ -220,7 +220,7 @@ func (registry *interfaceRegistry) RegisterCustomTypeURL(iface interface{}, type // // This function PANICs if different concrete types are registered under the // same typeURL. -func (registry *interfaceRegistry) registerImpl(iface interface{}, typeURL string, impl proto.Message) { +func (registry *interfaceRegistry) registerImpl(iface any, typeURL string, impl proto.Message) { ityp := reflect.TypeOf(iface).Elem() imap, found := registry.interfaceImpls[ityp] if !found { @@ -283,7 +283,7 @@ func (registry *interfaceRegistry) ListImplementations(ifaceName string) []strin return keys } -func (registry *interfaceRegistry) UnpackAny(any *Any, iface interface{}) error { +func (registry *interfaceRegistry) UnpackAny(any *Any, iface any) error { unpacker := &statefulUnpacker{ registry: registry, maxDepth: MaxUnpackAnyRecursionDepth, diff --git a/crypto/keys/bcrypt/base64.go b/crypto/keys/bcrypt/base64.go index fc31160908..961ef6223f 100644 --- a/crypto/keys/bcrypt/base64.go +++ b/crypto/keys/bcrypt/base64.go @@ -22,7 +22,7 @@ func base64Encode(src []byte) []byte { func base64Decode(src []byte) ([]byte, error) { numOfEquals := 4 - (len(src) % 4) - for i := 0; i < numOfEquals; i++ { + for range numOfEquals { src = append(src, '=') } diff --git a/crypto/keys/bcrypt/bcrypt.go b/crypto/keys/bcrypt/bcrypt.go index f4f62d500c..442d9fbb3a 100644 --- a/crypto/keys/bcrypt/bcrypt.go +++ b/crypto/keys/bcrypt/bcrypt.go @@ -191,7 +191,7 @@ func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, error) { } for i := 0; i < 24; i += 8 { - for j := 0; j < 64; j++ { + for range 64 { c.Encrypt(cipherData[i:i+8], cipherData[i:i+8]) } } @@ -218,9 +218,8 @@ func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cip return nil, err } - var i, rounds uint64 - rounds = 1 << cost - for i = 0; i < rounds; i++ { + var rounds uint64 = 1 << cost + for range rounds { blowfish.ExpandKey(ckey, c) blowfish.ExpandKey(csalt, c) } @@ -239,7 +238,7 @@ func (p *hashed) Hash() []byte { } arr[n] = '$' n++ - copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost))) + copy(arr[n:], fmt.Appendf(nil, "%02d", p.cost)) n += 2 arr[n] = '$' n++ diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 57c6f0563f..70956aa48c 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -139,7 +139,7 @@ func TestMarshalAmino(t *testing.T) { testCases := []struct { desc string msg codec.AminoMarshaler - typ interface{} + typ any expBinary []byte expJSON string }{ @@ -195,9 +195,9 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { testCases := []struct { desc string - tmKey interface{} - ourKey interface{} - marshalFn func(o interface{}) ([]byte, error) + tmKey any + ourKey any + marshalFn func(o any) ([]byte, error) }{ { "ed25519 private key, binary", diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index 10f7d2e040..dbe8688140 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -68,7 +68,7 @@ func (m *LegacyAminoPubKey) VerifyMultisignature(getSignBytes multisigtypes.GetS } // index in the list of signatures which we are concerned with. sigIndex := 0 - for i := 0; i < size; i++ { + for i := range size { if bitarray.GetIndex(i) { si := sig.Signatures[sigIndex] switch si := si.(type) { @@ -108,7 +108,7 @@ func (m *LegacyAminoPubKey) VerifySignature(msg, sig []byte) bool { func (m *LegacyAminoPubKey) GetPubKeys() []cryptotypes.PubKey { if m != nil { pubKeys := make([]cryptotypes.PubKey, len(m.PubKeys)) - for i := 0; i < len(m.PubKeys); i++ { + for i := range m.PubKeys { pubKeys[i] = m.PubKeys[i].GetCachedValue().(cryptotypes.PubKey) } return pubKeys @@ -130,7 +130,7 @@ func (m *LegacyAminoPubKey) Equals(key cryptotypes.PubKey) bool { return false } - for i := 0; i < len(pubKeys); i++ { + for i := range pubKeys { if !pubKeys[i].Equals(otherPubKeys[i]) { return false } @@ -163,7 +163,7 @@ func (m *LegacyAminoPubKey) UnpackInterfaces(unpacker types.AnyUnpacker) error { func packPubKeys(pubKeys []cryptotypes.PubKey) ([]*types.Any, error) { anyPubKeys := make([]*types.Any, len(pubKeys)) - for i := 0; i < len(pubKeys); i++ { + for i := range pubKeys { any, err := types.NewAnyWithValue(pubKeys[i]) if err != nil { return nil, err diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 3fa46e35d0..498dbc168c 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -134,7 +134,7 @@ func TestVerifyMultisignature(t *testing.T) { sig = multisig.NewMultisig(len(pubKeys)) signBytesFn := func(mode signing.SignMode) ([]byte, error) { return msg, nil } - for i := 0; i < k-1; i++ { + for i := range k - 1 { signingIndex := signingIndices[i] require.NoError( multisig.AddSignatureFromPubKey(sig, sigs[signingIndex], pubKeys[signingIndex], pubKeys), @@ -298,7 +298,7 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { func generatePubKeys(n int) []cryptotypes.PubKey { pks := make([]cryptotypes.PubKey, n) - for i := 0; i < n; i++ { + for i := range n { pks[i] = secp256k1.GenPrivKey().PubKey() } return pks @@ -308,7 +308,7 @@ func generatePubKeysAndSignatures(n int, msg []byte) (pubKeys []cryptotypes.PubK pubKeys = make([]cryptotypes.PubKey, n) signatures = make([]signing.SignatureData, n) - for i := 0; i < n; i++ { + for i := range n { privkey := secp256k1.GenPrivKey() pubKeys[i] = privkey.PubKey() @@ -322,10 +322,10 @@ func generateNestedMultiSignature(n int, msg []byte) (multisig.PubKey, *signing. pubKeys := make([]cryptotypes.PubKey, n) signatures := make([]signing.SignatureData, n) bitArray := cryptotypes.NewCompactBitArray(n) - for i := 0; i < n; i++ { + for i := range n { nestedPks, nestedSigs := generatePubKeysAndSignatures(5, msg) nestedBitArray := cryptotypes.NewCompactBitArray(5) - for j := 0; j < 5; j++ { + for j := range 5 { nestedBitArray.SetIndex(j, true) } nestedSig := &signing.MultiSignatureData{ diff --git a/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go b/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go index 080f885640..b156d36cd6 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go +++ b/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go @@ -148,7 +148,7 @@ func TestRandomMessagesWithRandomKeys(t *testing.T) { } func signAndRecoverWithRandomMessages(t *testing.T, keys func() ([]byte, []byte)) { - for i := 0; i < TestCount; i++ { + for range TestCount { pubkey1, seckey := keys() msg := csprngEntropy(32) sig, err := Sign(msg, seckey) @@ -180,7 +180,7 @@ func TestRecoveryOfRandomSignature(t *testing.T) { pubkey1, _ := generateKeyPair() msg := csprngEntropy(32) - for i := 0; i < TestCount; i++ { + for i := range TestCount { // recovery can sometimes work, but if so should always give wrong pubkey pubkey2, _ := RecoverPubkey(msg, randSig()) if bytes.Equal(pubkey1, pubkey2) { @@ -194,7 +194,7 @@ func TestRandomMessagesAgainstValidSig(t *testing.T) { msg := csprngEntropy(32) sig, _ := Sign(msg, seckey) - for i := 0; i < TestCount; i++ { + for i := range TestCount { msg = csprngEntropy(32) pubkey2, _ := RecoverPubkey(msg, sig) // recovery can sometimes work, but if so should always give wrong pubkey diff --git a/crypto/keys/secp256k1/secp256k1_nocgo_test.go b/crypto/keys/secp256k1/secp256k1_nocgo_test.go index ffea5d82d7..9aff83f9f3 100644 --- a/crypto/keys/secp256k1/secp256k1_nocgo_test.go +++ b/crypto/keys/secp256k1/secp256k1_nocgo_test.go @@ -15,7 +15,7 @@ import ( // Note: run with CGO_ENABLED=0 or go test -tags !cgo. func TestSignatureVerificationAndRejectUpperS(t *testing.T) { msg := []byte("We have lingered long enough on the shores of the cosmic ocean.") - for i := 0; i < 500; i++ { + for range 500 { priv := GenPrivKey() sigStr, err := priv.Sign(msg) require.NoError(t, err) diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index a1cd922547..da5b293072 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -220,7 +220,7 @@ func TestSignAndValidateSecp256k1(t *testing.T) { // in creating the privkey. func TestSecp256k1LoadPrivkeyAndSerializeIsIdentity(t *testing.T) { numberOfTests := 256 - for i := 0; i < numberOfTests; i++ { + for range numberOfTests { // Seed the test case with some random bytes privKeyBytes := [32]byte{} copy(privKeyBytes[:], crypto.CRandBytes(32)) @@ -352,7 +352,7 @@ func TestMarshalAmino(t *testing.T) { testCases := []struct { desc string msg codec.AminoMarshaler - typ interface{} + typ any expBinary []byte expJSON string }{ @@ -408,9 +408,9 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { testCases := []struct { desc string - tmKey interface{} - ourKey interface{} - marshalFn func(o interface{}) ([]byte, error) + tmKey any + ourKey any + marshalFn func(o any) ([]byte, error) }{ { "secp256k1 private key, binary", diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index a181f1fa5f..6f28dfa169 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -8,7 +8,7 @@ import ( cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) -func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { +func checkAminoJSON(t *testing.T, src, dst any, isNil bool) { t.Helper() // Marshal to JSON bytes. diff --git a/crypto/types/compact_bit_array.go b/crypto/types/compact_bit_array.go index 8761d21f63..d09ac61b6e 100644 --- a/crypto/types/compact_bit_array.go +++ b/crypto/types/compact_bit_array.go @@ -147,7 +147,7 @@ func (bA *CompactBitArray) StringIndented(indent string) string { lines := []string{} bits := "" size := bA.Count() - for i := 0; i < size; i++ { + for i := range size { if bA.GetIndex(i) { bits += "x" } else { @@ -184,7 +184,7 @@ func (bA *CompactBitArray) MarshalJSON() ([]byte, error) { bits := `"` size := bA.Count() - for i := 0; i < size; i++ { + for i := range size { if bA.GetIndex(i) { bits += `x` } else { @@ -222,7 +222,7 @@ func (bA *CompactBitArray) UnmarshalJSON(bz []byte) error { // Construct new CompactBitArray and copy over. numBits := len(bits) bA2 := NewCompactBitArray(numBits) - for i := 0; i < numBits; i++ { + for i := range numBits { if bits[i] == 'x' { bA2.SetIndex(i, true) } diff --git a/crypto/types/compact_bit_array_test.go b/crypto/types/compact_bit_array_test.go index 1f7f276cff..09b18818f1 100644 --- a/crypto/types/compact_bit_array_test.go +++ b/crypto/types/compact_bit_array_test.go @@ -18,7 +18,7 @@ func randCompactBitArray(bits int) (*CompactBitArray, []byte) { src := unsafe.Bytes((bits + 7) / 8) bA := NewCompactBitArray(bits) - for i := 0; i < numBytes-1; i++ { + for i := range numBytes - 1 { for j := uint8(0); j < 8; j++ { bA.SetIndex(i*8+int(j), src[i]&(uint8(1)<<(8-j)) > 0) } @@ -211,7 +211,7 @@ func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) { err := json.Unmarshal([]byte(tc.marshalledBA), &bA) require.NoError(t, err) - for i := 0; i < len(tc.bAIndex); i++ { + for i := range tc.bAIndex { require.Equal(t, tc.trueValueIndex[i], bA.NumTrueBitsBefore(tc.bAIndex[i]), "tc %d, i %d", tcIndex, i) } }) @@ -222,11 +222,11 @@ func TestCompactBitArrayGetSetIndex(t *testing.T) { r := rand.New(rand.NewSource(100)) numTests := 10 numBitsPerArr := 100 - for i := 0; i < numTests; i++ { + for range numTests { bits := r.Intn(1000) bA, _ := randCompactBitArray(bits) - for j := 0; j < numBitsPerArr; j++ { + for range numBitsPerArr { copy := bA.Copy() index := r.Intn(bits) val := (r.Int63() % 2) == 0 diff --git a/crypto/types/multisig/multisignature.go b/crypto/types/multisig/multisignature.go index f5aaea754a..12f2e799f9 100644 --- a/crypto/types/multisig/multisignature.go +++ b/crypto/types/multisig/multisignature.go @@ -27,7 +27,7 @@ func NewMultisig(n int) *signing.MultiSignatureData { // GetIndex returns the index of pk in keys. Returns -1 if not found func getIndex(pk types.PubKey, keys []types.PubKey) int { - for i := 0; i < len(keys); i++ { + for i := range keys { if pk.Equals(keys[i]) { return i } diff --git a/internal/conv/string_test.go b/internal/conv/string_test.go index 3a14517531..e6f24ec7b9 100644 --- a/internal/conv/string_test.go +++ b/internal/conv/string_test.go @@ -22,7 +22,7 @@ func unsafeConvertStr() []byte { func (s *StringSuite) TestUnsafeStrToBytes() { // we convert in other function to trigger GC. We want to check that // the underlying array in []bytes is accessible after GC will finish swapping. - for i := 0; i < 5; i++ { + for range 5 { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C @@ -39,7 +39,7 @@ func unsafeConvertBytes() string { func (s *StringSuite) TestUnsafeBytesToStr() { // we convert in other function to trigger GC. We want to check that // the underlying array in []bytes is accessible after GC will finish swapping. - for i := 0; i < 5; i++ { + for range 5 { str := unsafeConvertBytes() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C diff --git a/runtime/services/autocli.go b/runtime/services/autocli.go index 66c70b31e7..7290b8fc0f 100644 --- a/runtime/services/autocli.go +++ b/runtime/services/autocli.go @@ -25,7 +25,7 @@ type AutoCLIQueryService struct { } // NewAutoCLIQueryService returns a AutoCLIQueryService for the provided modules. -func NewAutoCLIQueryService(appModules map[string]interface{}) *AutoCLIQueryService { +func NewAutoCLIQueryService(appModules map[string]any) *AutoCLIQueryService { return &AutoCLIQueryService{ moduleOptions: ExtractAutoCLIOptions(appModules), } @@ -36,7 +36,7 @@ func NewAutoCLIQueryService(appModules map[string]interface{}) *AutoCLIQueryServ // Example Usage: // // ExtractAutoCLIOptions(ModuleManager.Modules) -func ExtractAutoCLIOptions(appModules map[string]interface{}) map[string]*autocliv1.ModuleOptions { +func ExtractAutoCLIOptions(appModules map[string]any) map[string]*autocliv1.ModuleOptions { moduleOptions := map[string]*autocliv1.ModuleOptions{} for modName, mod := range appModules { if autoCliMod, ok := mod.(interface { @@ -113,7 +113,7 @@ func (a *autocliConfigurator) RegisterMigration(string, uint64, module.Migration return nil } -func (a *autocliConfigurator) RegisterService(sd *grpc.ServiceDesc, ss interface{}) { +func (a *autocliConfigurator) RegisterService(sd *grpc.ServiceDesc, ss any) { if a.registryCache == nil { a.registryCache, a.err = proto.MergedRegistry() } @@ -137,7 +137,7 @@ type autocliServiceRegistrar struct { serviceName string } -func (a *autocliServiceRegistrar) RegisterService(sd *grpc.ServiceDesc, _ interface{}) { +func (a *autocliServiceRegistrar) RegisterService(sd *grpc.ServiceDesc, _ any) { a.serviceName = sd.ServiceName } diff --git a/server/config/config_test.go b/server/config/config_test.go index bd5cf061b3..f516aa826a 100644 --- a/server/config/config_test.go +++ b/server/config/config_test.go @@ -163,9 +163,9 @@ func TestGlobalLabelsEventsMarshalling(t *testing.T) { func TestGlobalLabelsWriteRead(t *testing.T) { expected := [][]string{{"labelname3", "labelvalue3"}, {"labelname4", "labelvalue4"}} - expectedRaw := make([]interface{}, len(expected)) + expectedRaw := make([]any, len(expected)) for i, exp := range expected { - pair := make([]interface{}, len(exp)) + pair := make([]any, len(exp)) for j, s := range exp { pair[j] = s } diff --git a/server/config/toml.go b/server/config/toml.go index b3c20c69a0..ccd050a3aa 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -283,7 +283,7 @@ func SetConfigTemplate(customTemplate string) { // WriteConfigFile renders config using the template and writes it to // configFilePath. -func WriteConfigFile(configFilePath string, config interface{}) { +func WriteConfigFile(configFilePath string, config any) { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil { diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index 963cf0cd79..0fdc425302 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -309,7 +309,7 @@ func (s *serverReflectionServer) fileDescEncodingByFilename(name string, sentFil // For SupportPackageIsVersion4, m is the name of the proto file, we // call proto.FileDescriptor to get the byte slice. // For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) ([]byte, bool) { +func parseMetadata(meta any) ([]byte, bool) { // Check if meta is the file name. if fileNameForMeta, ok := meta.(string); ok { return getFileDescriptor(fileNameForMeta), true diff --git a/server/log/cmt_logger.go b/server/log/cmt_logger.go index 9cc9380372..832e9d5213 100644 --- a/server/log/cmt_logger.go +++ b/server/log/cmt_logger.go @@ -17,7 +17,7 @@ type CometLoggerWrapper struct { // With returns a new wrapped logger with additional context provided by a set // of key/value tuples. The number of tuples must be even and the key of the // tuple must be a string. -func (cmt CometLoggerWrapper) With(keyVals ...interface{}) cmtlog.Logger { +func (cmt CometLoggerWrapper) With(keyVals ...any) cmtlog.Logger { logger := cmt.Logger.With(keyVals...) return CometLoggerWrapper{logger} } diff --git a/server/mock/app.go b/server/mock/app.go index f090f8c6df..864f1a5d03 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -153,7 +153,7 @@ type MsgServerImpl struct { capKeyMainStore *storetypes.KVStoreKey } -func MsgTestHandler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func MsgTestHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) { in := new(KVStoreTx) if err := dec(in); err != nil { return nil, err @@ -165,7 +165,7 @@ func MsgTestHandler(srv interface{}, ctx context.Context, dec func(interface{}) Server: srv, FullMethod: "/KVStoreTx", } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { return srv.(MsgServer).Test(ctx, req.(*KVStoreTx)) } return interceptor(ctx, in, info, handler) diff --git a/server/start.go b/server/start.go index 1c9401703d..ff540c514d 100644 --- a/server/start.go +++ b/server/start.go @@ -829,7 +829,7 @@ func testnetify(ctx *Context, testnetAppCreator types.AppCreator, db dbm.DB, tra state.AppHash = appHash } else { // Node was likely stopped via SIGTERM, delete the next block's seen commit - err := blockStoreDB.Delete([]byte(fmt.Sprintf("SC:%v", blockStore.Height()+1))) + err := blockStoreDB.Delete(fmt.Appendf(nil, "SC:%v", blockStore.Height()+1)) if err != nil { return nil, err } @@ -928,19 +928,19 @@ func testnetify(ctx *Context, testnetAppCreator types.AppCreator, db dbm.DB, tra } // Modfiy Validators stateDB entry. - err = stateDB.Set([]byte(fmt.Sprintf("validatorsKey:%v", blockStore.Height())), buf) + err = stateDB.Set(fmt.Appendf(nil, "validatorsKey:%v", blockStore.Height()), buf) if err != nil { return nil, err } // Modify LastValidators stateDB entry. - err = stateDB.Set([]byte(fmt.Sprintf("validatorsKey:%v", blockStore.Height()-1)), buf) + err = stateDB.Set(fmt.Appendf(nil, "validatorsKey:%v", blockStore.Height()-1), buf) if err != nil { return nil, err } // Modify NextValidators stateDB entry. - err = stateDB.Set([]byte(fmt.Sprintf("validatorsKey:%v", blockStore.Height()+1)), buf) + err = stateDB.Set(fmt.Appendf(nil, "validatorsKey:%v", blockStore.Height()+1), buf) if err != nil { return nil, err } diff --git a/server/types/app.go b/server/types/app.go index 9eac5ed27c..4841893c15 100644 --- a/server/types/app.go +++ b/server/types/app.go @@ -28,7 +28,7 @@ type ( // the expected types and could result in type assertion errors. It is recommend // to either use the cast package or perform manual conversion for safety. AppOptions interface { - Get(string) interface{} + Get(string) any } // Application defines an application interface that wraps abci.Application. diff --git a/server/util.go b/server/util.go index 850afe1136..9957a3a5d9 100644 --- a/server/util.go +++ b/server/util.go @@ -99,7 +99,7 @@ func bindFlags(basename string, cmd *cobra.Command, v *viper.Viper) (err error) // InterceptConfigsPreRunHandler is identical to InterceptConfigsAndCreateContext // except it also sets the server context on the command and the server logger. -func InterceptConfigsPreRunHandler(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig interface{}, cmtConfig *cmtcfg.Config) error { +func InterceptConfigsPreRunHandler(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig any, cmtConfig *cmtcfg.Config) error { serverCtx, err := InterceptConfigsAndCreateContext(cmd, customAppConfigTemplate, customAppConfig, cmtConfig) if err != nil { return err @@ -126,7 +126,7 @@ func InterceptConfigsPreRunHandler(cmd *cobra.Command, customAppConfigTemplate s // is used to read and parse the application configuration. Command handlers can // fetch the server Context to get the CometBFT configuration or to get access // to Viper. -func InterceptConfigsAndCreateContext(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig interface{}, cmtConfig *cmtcfg.Config) (*Context, error) { +func InterceptConfigsAndCreateContext(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig any, cmtConfig *cmtcfg.Config) (*Context, error) { serverCtx := NewDefaultContext() // Get the executable name and configure the viper instance so that environmental @@ -231,7 +231,7 @@ func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error { // configuration file. The CometBFT configuration file is parsed given a root // Viper object, whereas the application is parsed with the private package-aware // viperCfg object. -func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customConfig interface{}, cmtConfig *cmtcfg.Config) (*cmtcfg.Config, error) { +func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customConfig any, cmtConfig *cmtcfg.Config) (*cmtcfg.Config, error) { rootDir := rootViper.GetString(flags.FlagHome) configPath := filepath.Join(rootDir, "config") cmtCfgFile := filepath.Join(configPath, "config.toml") diff --git a/server/util_test.go b/server/util_test.go index 9c55cb6560..a5f22758df 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -460,9 +460,9 @@ func TestEmptyMinGasPrices(t *testing.T) { require.Errorf(t, err, sdkerrors.ErrAppConfig.Error()) } -type mapGetter map[string]interface{} +type mapGetter map[string]any -func (m mapGetter) Get(key string) interface{} { +func (m mapGetter) Get(key string) any { return m[key] } diff --git a/simsx/delivery.go b/simsx/delivery.go index ca784d2904..80237a1cf6 100644 --- a/simsx/delivery.go +++ b/simsx/delivery.go @@ -65,7 +65,7 @@ func DeliverSimsMsg( } accountNumbers := make([]uint64, len(senders)) sequenceNumbers := make([]uint64, len(senders)) - for i := 0; i < len(senders); i++ { + for i := range senders { acc := ak.GetAccount(ctx, senders[i].Address) accountNumbers[i] = acc.GetAccountNumber() sequenceNumbers[i] = acc.GetSequence() diff --git a/simsx/slices.go b/simsx/slices.go index 3466cd6f97..a454731f89 100644 --- a/simsx/slices.go +++ b/simsx/slices.go @@ -23,7 +23,7 @@ func Collect[T, E any](source []T, f func(a T) E) []E { // First returns the first element in the slice that matches the condition func First[T any](source []T, f func(a T) bool) *T { - for i := 0; i < len(source); i++ { + for i := range source { if f(source[i]) { return &source[i] } diff --git a/telemetry/metrics_test.go b/telemetry/metrics_test.go index b18c33cac6..b741f007db 100644 --- a/telemetry/metrics_test.go +++ b/telemetry/metrics_test.go @@ -32,12 +32,12 @@ func TestMetrics_InMem(t *testing.T) { require.NoError(t, err) require.Equal(t, gr.ContentType, "application/json") - jsonMetrics := make(map[string]interface{}) + jsonMetrics := make(map[string]any) require.NoError(t, json.Unmarshal(gr.Metrics, &jsonMetrics)) - counters := jsonMetrics["Counters"].([]interface{}) - require.Equal(t, counters[0].(map[string]interface{})["Count"].(float64), 10.0) - require.Equal(t, counters[0].(map[string]interface{})["Name"].(string), "test.dummy_counter") + counters := jsonMetrics["Counters"].([]any) + require.Equal(t, counters[0].(map[string]any)["Count"].(float64), 10.0) + require.Equal(t, counters[0].(map[string]any)["Name"].(string), "test.dummy_counter") } func TestMetrics_Prom(t *testing.T) { diff --git a/testutil/cli/tx.go b/testutil/cli/tx.go index b033657a3d..80246c9f8c 100644 --- a/testutil/cli/tx.go +++ b/testutil/cli/tx.go @@ -14,7 +14,7 @@ import ( // Takes a network, wait for two blocks and fetch the transaction from its hash func CheckTxCode(network *network.Network, clientCtx client.Context, txHash string, expectedCode uint32) error { // wait for 2 blocks - for i := 0; i < 2; i++ { + for range 2 { if err := network.WaitForNextBlock(); err != nil { return fmt.Errorf("failed to wait for next block: %w", err) } @@ -42,7 +42,7 @@ func CheckTxCode(network *network.Network, clientCtx client.Context, txHash stri // Takes a network, wait for two blocks and fetch the transaction from its hash func GetTxResponse(network *network.Network, clientCtx client.Context, txHash string) (sdk.TxResponse, error) { // wait for 2 blocks - for i := 0; i < 2; i++ { + for range 2 { if err := network.WaitForNextBlock(); err != nil { return sdk.TxResponse{}, fmt.Errorf("failed to wait for next block: %w", err) } diff --git a/testutil/compare.go b/testutil/compare.go index 3e795e8f3f..36da8715ff 100644 --- a/testutil/compare.go +++ b/testutil/compare.go @@ -10,7 +10,7 @@ import ( // RequireProtoDeepEqual fails the test t if p1 and p2 are not equivalent protobuf messages. // Where p1 and p2 are proto.Message or slices of proto.Message. -func RequireProtoDeepEqual(t *testing.T, p1, p2 interface{}) { +func RequireProtoDeepEqual(t *testing.T, p1, p2 any) { t.Helper() require.Empty(t, cmp.Diff(p1, p2, protocmp.Transform())) } diff --git a/testutil/mock/types_handler.go b/testutil/mock/types_handler.go index 06f6037192..5c1d8c8aff 100644 --- a/testutil/mock/types_handler.go +++ b/testutil/mock/types_handler.go @@ -47,7 +47,7 @@ func (m *MockAnteDecorator) AnteHandle(ctx types.Context, tx types.Tx, simulate } // AnteHandle indicates an expected call of AnteHandle. -func (mr *MockAnteDecoratorMockRecorder) AnteHandle(ctx, tx, simulate, next interface{}) *gomock.Call { +func (mr *MockAnteDecoratorMockRecorder) AnteHandle(ctx, tx, simulate, next any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AnteHandle", reflect.TypeOf((*MockAnteDecorator)(nil).AnteHandle), ctx, tx, simulate, next) } @@ -84,7 +84,7 @@ func (m *MockPostDecorator) PostHandle(ctx types.Context, tx types.Tx, simulate, } // PostHandle indicates an expected call of PostHandle. -func (mr *MockPostDecoratorMockRecorder) PostHandle(ctx, tx, simulate, success, next interface{}) *gomock.Call { +func (mr *MockPostDecoratorMockRecorder) PostHandle(ctx, tx, simulate, success, next any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostHandle", reflect.TypeOf((*MockPostDecorator)(nil).PostHandle), ctx, tx, simulate, success, next) } diff --git a/testutil/network/network.go b/testutil/network/network.go index 1c2edfa2da..58c9c1b79e 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -70,7 +70,7 @@ var ( func init() { closeFns := []func() error{} - for i := 0; i < 200; i++ { + for range 200 { _, port, closeFn, err := FreeTCPAddr() if err != nil { panic(err) @@ -304,8 +304,8 @@ type ( // Logger is a network logger interface that exposes testnet-level Log() methods for an in-process testing network // This is not to be confused with logging that may happen at an individual node or validator level Logger interface { - Log(args ...interface{}) - Logf(format string, args ...interface{}) + Log(args ...any) + Logf(format string, args ...any) } ) @@ -329,12 +329,12 @@ type CLILogger struct { } // Log logs given args. -func (s CLILogger) Log(args ...interface{}) { +func (s CLILogger) Log(args ...any) { s.cmd.Println(args...) } // Logf logs given args according to a format specifier. -func (s CLILogger) Logf(format string, args ...interface{}) { +func (s CLILogger) Logf(format string, args ...any) { s.cmd.Printf(format, args...) } @@ -371,7 +371,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { buf := bufio.NewReader(os.Stdin) // generate private keys, node IDs, and initial transactions - for i := 0; i < cfg.NumValidators; i++ { + for i := range cfg.NumValidators { appCfg := srvconfig.DefaultConfig() appCfg.Pruning = cfg.PruningStrategy appCfg.MinGasPrices = cfg.MinGasPrices @@ -757,7 +757,7 @@ func (n *Network) WaitForHeightWithTimeout(h int64, t time.Duration) (int64, err // It will do this until the function returns a nil error or until the number of // blocks has been reached. func (n *Network) RetryForBlocks(retryFunc func() error, blocks int) error { - for i := 0; i < blocks; i++ { + for i := range blocks { _ = n.WaitForNextBlock() // ignore the error as we use the retry for validation err := retryFunc() if err == nil { diff --git a/testutil/network/util.go b/testutil/network/util.go index 072184cea2..87c833d268 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -128,7 +128,7 @@ func startInProcess(cfg Config, val *Validator) error { func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { genTime := cmttime.Now() - for i := 0; i < cfg.NumValidators; i++ { + for i := range cfg.NumValidators { cmtCfg := vals[i].Ctx.Config nodeDir := filepath.Join(outputDir, vals[i].Moniker, "simd") @@ -194,7 +194,7 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance } // generate empty genesis files for each validator and save - for i := 0; i < cfg.NumValidators; i++ { + for i := range cfg.NumValidators { if err := appGenesis.SaveAs(genFiles[i]); err != nil { return err } diff --git a/testutil/sims/address_helpers.go b/testutil/sims/address_helpers.go index 4bd7ef65e4..d54ebb8818 100644 --- a/testutil/sims/address_helpers.go +++ b/testutil/sims/address_helpers.go @@ -101,7 +101,7 @@ func CreateIncrementalAccounts(accNum int) []sdk.AccAddress { // CreateRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order. func CreateRandomAccounts(accNum int) []sdk.AccAddress { testAddrs := make([]sdk.AccAddress, accNum) - for i := 0; i < accNum; i++ { + for i := range accNum { pk := ed25519.GenPrivKey().PubKey() testAddrs[i] = sdk.AccAddress(pk.Address()) } diff --git a/testutil/sims/app_helpers.go b/testutil/sims/app_helpers.go index d8de07851b..0d2f612b7e 100644 --- a/testutil/sims/app_helpers.go +++ b/testutil/sims/app_helpers.go @@ -96,13 +96,13 @@ func DefaultStartUpConfig() StartupConfig { // Setup initializes a new runtime.App and can inject values into extraOutputs. // It uses SetupWithConfiguration under the hood. -func Setup(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) { +func Setup(appConfig depinject.Config, extraOutputs ...any) (*runtime.App, error) { return SetupWithConfiguration(appConfig, DefaultStartUpConfig(), extraOutputs...) } // SetupAtGenesis initializes a new runtime.App at genesis and can inject values into extraOutputs. // It uses SetupWithConfiguration under the hood. -func SetupAtGenesis(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) { +func SetupAtGenesis(appConfig depinject.Config, extraOutputs ...any) (*runtime.App, error) { cfg := DefaultStartUpConfig() cfg.AtGenesis = true return SetupWithConfiguration(appConfig, cfg, extraOutputs...) @@ -136,7 +136,7 @@ func NextBlock(app *runtime.App, ctx sdk.Context, jumpTime time.Duration) (sdk.C // SetupWithConfiguration initializes a new runtime.App. A Nop logger is set in runtime.App. // appConfig defines the application configuration (f.e. app_config.go). // extraOutputs defines the extra outputs to be assigned by the dependency injector (depinject). -func SetupWithConfiguration(appConfig depinject.Config, startupConfig StartupConfig, extraOutputs ...interface{}) (*runtime.App, error) { +func SetupWithConfiguration(appConfig depinject.Config, startupConfig StartupConfig, extraOutputs ...any) (*runtime.App, error) { // create the app with depinject var ( app *runtime.App @@ -285,17 +285,17 @@ func GenesisStateWithValSet( type EmptyAppOptions struct{} // Get implements AppOptions -func (ao EmptyAppOptions) Get(o string) interface{} { +func (ao EmptyAppOptions) Get(o string) any { return nil } // AppOptionsMap is a stub implementing AppOptions which can get data from a map -type AppOptionsMap map[string]interface{} +type AppOptionsMap map[string]any -func (m AppOptionsMap) Get(key string) interface{} { +func (m AppOptionsMap) Get(key string) any { v, ok := m[key] if !ok { - return interface{}(nil) + return any(nil) } return v diff --git a/testutil/sims/simulation_helpers.go b/testutil/sims/simulation_helpers.go index cf432a6c40..ef5fa4ab58 100644 --- a/testutil/sims/simulation_helpers.go +++ b/testutil/sims/simulation_helpers.go @@ -123,7 +123,7 @@ func PrintStats(db dbm.DB) { // GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the // each's module store key and the prefix bytes of the KVPair's key. func GetSimulationLog(storeName string, sdr simtypes.StoreDecoderRegistry, kvAs, kvBs []kv.Pair) (log string) { - for i := 0; i < len(kvAs); i++ { + for i := range kvAs { if len(kvAs[i].Value) == 0 && len(kvBs[i].Value) == 0 { // skip if the value doesn't have any bytes continue diff --git a/testutil/sims/state_helpers.go b/testutil/sims/state_helpers.go index 6605be4eea..20ca16f142 100644 --- a/testutil/sims/state_helpers.go +++ b/testutil/sims/state_helpers.go @@ -65,7 +65,7 @@ func AppStateFnWithExtendedCbs( cdc codec.JSONCodec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage, - moduleStateCb func(moduleName string, genesisState interface{}), + moduleStateCb func(moduleName string, genesisState any), rawStateCb func(rawState map[string]json.RawMessage), ) simtypes.AppStateFn { return func( diff --git a/types/address.go b/types/address.go index 64bafffe79..a918e10cb2 100644 --- a/types/address.go +++ b/types/address.go @@ -244,7 +244,7 @@ func (aa AccAddress) MarshalJSON() ([]byte, error) { } // MarshalYAML marshals to YAML using Bech32. -func (aa AccAddress) MarshalYAML() (interface{}, error) { +func (aa AccAddress) MarshalYAML() (any, error) { return aa.String(), nil } @@ -406,7 +406,7 @@ func (va ValAddress) MarshalJSON() ([]byte, error) { } // MarshalYAML marshals to YAML using Bech32. -func (va ValAddress) MarshalYAML() (interface{}, error) { +func (va ValAddress) MarshalYAML() (any, error) { return va.String(), nil } @@ -566,7 +566,7 @@ func (ca ConsAddress) MarshalJSON() ([]byte, error) { } // MarshalYAML marshals to YAML using Bech32. -func (ca ConsAddress) MarshalYAML() (interface{}, error) { +func (ca ConsAddress) MarshalYAML() (any, error) { return ca.String(), nil } diff --git a/types/address/hash_test.go b/types/address/hash_test.go index b48a27e6ff..a52cd5d092 100644 --- a/types/address/hash_test.go +++ b/types/address/hash_test.go @@ -2,6 +2,7 @@ package address import ( "crypto/sha256" + "slices" "testing" "github.com/cometbft/cometbft/crypto/tmhash" @@ -40,7 +41,7 @@ func (suite *AddressSuite) TestComposed() { assert.Len(ac, Len) // check if optimizations work - checkingKey := append([]byte{}, a1.AddressWithLen(suite.T())...) + checkingKey := slices.Clone(a1.AddressWithLen(suite.T())) checkingKey = append(checkingKey, a2.AddressWithLen(suite.T())...) ac2 := Hash(typ, checkingKey) assert.Equal(ac, ac2, "NewComposed works correctly") diff --git a/types/address_race_test.go b/types/address_race_test.go index 5d363fda13..8e651a3be2 100644 --- a/types/address_race_test.go +++ b/types/address_race_test.go @@ -52,7 +52,7 @@ func (s *addressTestSuite) TestAddressRace() { close(cancel) // cleanup - for i := 0; i < 4; i++ { + for range 4 { <-done } } diff --git a/types/address_test.go b/types/address_test.go index 780fee0e62..b9a0a53522 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -44,7 +44,7 @@ var invalidStrs = []string{ types.Bech32PrefixConsPub + "6789", } -func (s *addressTestSuite) testMarshal(original, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { +func (s *addressTestSuite) testMarshal(original, res any, marshal func() ([]byte, error), unmarshal func([]byte) error) { bz, err := marshal() s.Require().Nil(err) s.Require().Nil(unmarshal(bz)) @@ -94,7 +94,7 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - for i := 0; i < 1000; i++ { + for range 1000 { _, err := rand.Read(pub.Key) s.Require().NoError(err) @@ -207,7 +207,7 @@ func (s *addressTestSuite) TestValAddr() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - for i := 0; i < 20; i++ { + for range 20 { _, err := rand.Read(pub.Key) s.Require().NoError(err) @@ -249,7 +249,7 @@ func (s *addressTestSuite) TestConsAddress() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - for i := 0; i < 20; i++ { + for range 20 { _, err := rand.Read(pub.Key) s.Require().NoError(err) diff --git a/types/coin.go b/types/coin.go index 72aaccd6c7..a052208289 100644 --- a/types/coin.go +++ b/types/coin.go @@ -676,7 +676,7 @@ func (coins Coins) Equal(coinsB Coins) bool { coins = coins.Sort() coinsB = coinsB.Sort() - for i := 0; i < len(coins); i++ { + for i := range coins { if !coins[i].Equal(coinsB[i]) { return false } diff --git a/types/coin_benchmark_test.go b/types/coin_benchmark_test.go index 188208d048..9c796bfdd1 100644 --- a/types/coin_benchmark_test.go +++ b/types/coin_benchmark_test.go @@ -20,10 +20,10 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) { coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) - for i := 0; i < numCoinsA; i++ { + for i := range numCoinsA { coinsA[i] = NewCoin(coinName(i), math.NewInt(int64(i))) } - for i := 0; i < numCoinsB; i++ { + for i := range numCoinsB { coinsB[i] = NewCoin(coinName(i), math.NewInt(int64(i))) } @@ -36,7 +36,7 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) { } benchmarkSizes := [][]int{{1, 1}, {5, 5}, {5, 20}, {1, 1000}, {2, 1000}} - for i := 0; i < len(benchmarkSizes); i++ { + for i := range benchmarkSizes { sizeA := benchmarkSizes[i][0] sizeB := benchmarkSizes[i][1] b.Run(fmt.Sprintf("sizes: A_%d, B_%d", sizeA, sizeB), benchmarkingFunc(sizeA, sizeB)) @@ -52,10 +52,10 @@ func BenchmarkCoinsAdditionNoIntersect(b *testing.B) { coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) - for i := 0; i < numCoinsA; i++ { + for i := range numCoinsA { coinsA[i] = NewCoin(coinName(numCoinsB+i), math.NewInt(int64(i))) } - for i := 0; i < numCoinsB; i++ { + for i := range numCoinsB { coinsB[i] = NewCoin(coinName(i), math.NewInt(int64(i))) } @@ -68,7 +68,7 @@ func BenchmarkCoinsAdditionNoIntersect(b *testing.B) { } benchmarkSizes := [][]int{{1, 1}, {5, 5}, {5, 20}, {1, 1000}, {2, 1000}, {1000, 2}} - for i := 0; i < len(benchmarkSizes); i++ { + for i := range benchmarkSizes { sizeA := benchmarkSizes[i][0] sizeB := benchmarkSizes[i][1] b.Run(fmt.Sprintf("sizes: A_%d, B_%d", sizeA, sizeB), benchmarkingFunc(sizeA, sizeB)) @@ -87,14 +87,14 @@ func BenchmarkSumOfCoinAdds(b *testing.B) { addCoins := make([]Coins, numAdds) nonIntersectingCoins := coinsPerAdd - numIntersectingCoins - for i := 0; i < numAdds; i++ { + for i := range numAdds { intersectCoins := make([]Coin, numIntersectingCoins) num := math.NewInt(int64(i)) - for j := 0; j < numIntersectingCoins; j++ { + for j := range numIntersectingCoins { intersectCoins[j] = NewCoin(coinName(j+1_000_000_000), num) } addCoins[i] = intersectCoins - for j := 0; j < nonIntersectingCoins; j++ { + for j := range nonIntersectingCoins { addCoins[i] = addCoins[i].Add(NewCoin(coinName(i*nonIntersectingCoins+j), num)) } } @@ -131,8 +131,8 @@ func BenchmarkSumOfCoinAdds(b *testing.B) { }{ {"MapCoins", MapCoinsSumFn}, {"Coins", CoinsSumFn}, } - for i := 0; i < len(benchmarkSizes); i++ { - for j := 0; j < 2; j++ { + for i := range benchmarkSizes { + for j := range 2 { coinsPerAdd := benchmarkSizes[i][0] intersectingCoinsPerAdd := benchmarkSizes[i][1] numAdds := benchmarkSizes[i][2] diff --git a/types/context.go b/types/context.go index b9605f00cf..5742ec41c8 100644 --- a/types/context.go +++ b/types/context.go @@ -322,12 +322,12 @@ func (c Context) IsZero() bool { return c.ms == nil } -func (c Context) WithValue(key, value interface{}) Context { +func (c Context) WithValue(key, value any) Context { c.baseCtx = context.WithValue(c.baseCtx, key, value) return c } -func (c Context) Value(key interface{}) interface{} { +func (c Context) Value(key any) any { if key == SdkContextKey { return c } diff --git a/types/dec_coin.go b/types/dec_coin.go index 87dad30782..7e1d16b481 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -490,7 +490,7 @@ func (coins DecCoins) Equal(coinsB DecCoins) bool { coins = coins.Sort() coinsB = coinsB.Sort() - for i := 0; i < len(coins); i++ { + for i := range coins { if !coins[i].Equal(coinsB[i]) { return false } diff --git a/types/events_test.go b/types/events_test.go index 49337f19fb..0b6b365d86 100644 --- a/types/events_test.go +++ b/types/events_test.go @@ -90,7 +90,7 @@ func (s *eventsTestSuite) TestEventManager() { func (s *eventsTestSuite) TestEmitTypedEvent() { s.Run("deterministic key-value order", func() { - for i := 0; i < 10; i++ { + for range 10 { em := sdk.NewEventManager() coin := sdk.NewCoin("fakedenom", math.NewInt(1999999)) s.Require().NoError(em.EmitTypedEvent(&coin)) diff --git a/types/handler.go b/types/handler.go index 456c3904e4..ffc90c2887 100644 --- a/types/handler.go +++ b/types/handler.go @@ -42,7 +42,7 @@ func ChainAnteDecorators(chain ...AnteDecorator) AnteHandler { handlerChain[len(chain)] = func(ctx Context, tx Tx, simulate bool) (Context, error) { return ctx, nil } - for i := 0; i < len(chain); i++ { + for i := range chain { ii := i handlerChain[ii] = func(ctx Context, tx Tx, simulate bool) (Context, error) { return chain[ii].AnteHandle(ctx, tx, simulate, handlerChain[ii+1]) @@ -70,7 +70,7 @@ func ChainPostDecorators(chain ...PostDecorator) PostHandler { handlerChain[len(chain)] = func(ctx Context, tx Tx, simulate, success bool) (Context, error) { return ctx, nil } - for i := 0; i < len(chain); i++ { + for i := range chain { ii := i handlerChain[ii] = func(ctx Context, tx Tx, simulate, success bool) (Context, error) { return chain[ii].PostHandle(ctx, tx, simulate, success, handlerChain[ii+1]) diff --git a/types/mempool/mempool_test.go b/types/mempool/mempool_test.go index e27ba8dcac..d84baaebaa 100644 --- a/types/mempool/mempool_test.go +++ b/types/mempool/mempool_test.go @@ -153,7 +153,7 @@ func (s *MempoolTestSuite) TestDefaultMempool() { txCount := 1000 var txs []testTx - for i := 0; i < txCount; i++ { + for i := range txCount { acc := accounts[i%len(accounts)] tx := testTx{ nonce: 0, diff --git a/types/mempool/priority_nonce_test.go b/types/mempool/priority_nonce_test.go index f4e5dd44ab..5bee608a46 100644 --- a/types/mempool/priority_nonce_test.go +++ b/types/mempool/priority_nonce_test.go @@ -497,7 +497,7 @@ func (s *MempoolTestSuite) TestPriorityTies() { {p: 10, n: 2, a: sa}, } - for i := 0; i < 100; i++ { + for range 100 { s.mempool = mempool.DefaultPriorityMempool() var shuffled []txSpec for _, t := range txSet { @@ -528,7 +528,7 @@ func (s *MempoolTestSuite) TestPriorityTies() { } func (s *MempoolTestSuite) TestRandomTxOrderManyTimes() { - for i := 0; i < 3; i++ { + for range 3 { s.Run("TestRandomGeneratedTxs", func() { s.TestRandomGeneratedTxs() }) @@ -663,7 +663,7 @@ func (s *MempoolTestSuite) TestRandomWalkTxs() { require.Equal(t, len(ordered), len(selected)) var orderedStr, selectedStr string - for i := 0; i < s.numTxs; i++ { + for i := range s.numTxs { otx := ordered[i] stx := selected[i].(testTx) orderedStr = fmt.Sprintf("%s\n%s, %d, %d; %d", @@ -693,7 +693,7 @@ func genRandomTxs(seed int64, countTx, countAccount int) (res []testTx) { accountNonces[account.Address.String()] = 0 } - for i := 0; i < countTx; i++ { + for i := range countTx { addr := accounts[r.Intn(countAccount)].Address priority := int64(r.Intn(maxPriority + 1)) nonce := accountNonces[addr.String()] diff --git a/types/module/configurator.go b/types/module/configurator.go index 970f868b36..57f66ec848 100644 --- a/types/module/configurator.go +++ b/types/module/configurator.go @@ -59,7 +59,7 @@ type configurator struct { } // RegisterService implements the grpc.Server interface. -func (c *configurator) RegisterService(sd *googlegrpc.ServiceDesc, ss interface{}) { +func (c *configurator) RegisterService(sd *googlegrpc.ServiceDesc, ss any) { desc, err := c.cdc.InterfaceRegistry().FindDescriptorByName(protoreflect.FullName(sd.ServiceName)) if err != nil { c.err = err diff --git a/types/module/module.go b/types/module/module.go index 834c1dd72e..4a39dc0971 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -276,7 +276,7 @@ func (gam GenesisOnlyAppModule) ConsensusVersion() uint64 { return 1 } // Manager defines a module manager that provides the high level utility for managing and executing // operations for a group of modules type Manager struct { - Modules map[string]interface{} // interface{} is used now to support the legacy AppModule as well as new core appmodule.AppModule. + Modules map[string]any // interface{} is used now to support the legacy AppModule as well as new core appmodule.AppModule. OrderInitGenesis []string OrderExportGenesis []string OrderPreBlockers []string @@ -289,7 +289,7 @@ type Manager struct { // NewManager creates a new Manager object. func NewManager(modules ...AppModule) *Manager { - moduleMap := make(map[string]interface{}) + moduleMap := make(map[string]any) modulesStr := make([]string, 0, len(modules)) preBlockModulesStr := make([]string, 0) for _, module := range modules { @@ -319,7 +319,7 @@ func NewManager(modules ...AppModule) *Manager { // NewManagerFromMap creates a new Manager object from a map of module names to module implementations. // This method should be used for apps and modules which have migrated to the cosmossdk.io/core.appmodule.AppModule API. func NewManagerFromMap(moduleMap map[string]appmodule.AppModule) *Manager { - simpleModuleMap := make(map[string]interface{}) + simpleModuleMap := make(map[string]any) modulesStr := make([]string, 0, len(simpleModuleMap)) preBlockModulesStr := make([]string, 0) for name, module := range moduleMap { diff --git a/types/module/module_int_test.go b/types/module/module_int_test.go index 443ee0bbcb..e8d66fcf3d 100644 --- a/types/module/module_int_test.go +++ b/types/module/module_int_test.go @@ -17,7 +17,7 @@ type TestSuite struct { func (s *TestSuite) TestAssertNoForgottenModules() { m := Manager{ - Modules: map[string]interface{}{"a": nil, "b": nil}, + Modules: map[string]any{"a": nil, "b": nil}, } tcs := []struct { name string @@ -42,7 +42,7 @@ func (s *TestSuite) TestAssertNoForgottenModules() { func (s *TestSuite) TestModuleNames() { m := Manager{ - Modules: map[string]interface{}{"a": nil, "b": nil}, + Modules: map[string]any{"a": nil, "b": nil}, } ms := m.ModuleNames() sort.Strings(ms) diff --git a/types/module/simulation.go b/types/module/simulation.go index 657bbfa2c2..56246acc99 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -61,7 +61,7 @@ func NewSimulationManager(modules ...AppModuleSimulation) *SimulationManager { // with the same moduleName. // Then it attempts to cast every provided AppModule into an AppModuleSimulation. // If the cast succeeds, its included, otherwise it is excluded. -func NewSimulationManagerFromAppModules(modules map[string]interface{}, overrideModules map[string]AppModuleSimulation) *SimulationManager { +func NewSimulationManagerFromAppModules(modules map[string]any, overrideModules map[string]AppModuleSimulation) *SimulationManager { simModules := []AppModuleSimulation{} appModuleNamesSorted := make([]string, 0, len(modules)) for moduleName := range modules { diff --git a/types/msgservice/msg_service.go b/types/msgservice/msg_service.go index 46de830f00..8e6a560e2e 100644 --- a/types/msgservice/msg_service.go +++ b/types/msgservice/msg_service.go @@ -41,7 +41,7 @@ func RegisterMsgServiceDesc(registry codectypes.InterfaceRegistry, sd *grpc.Serv } prefSd := fd.Services().ByName(protoreflect.FullName(sd.ServiceName).Name()) - for i := 0; i < prefSd.Methods().Len(); i++ { + for i := range prefSd.Methods().Len() { md := prefSd.Methods().Get(i) requestDesc := md.Input() responseDesc := md.Output() diff --git a/types/msgservice/validate.go b/types/msgservice/validate.go index 49a183eb89..0b3dd9e9d2 100644 --- a/types/msgservice/validate.go +++ b/types/msgservice/validate.go @@ -26,7 +26,7 @@ func ValidateProtoAnnotations(protoFiles signing.ProtoFileResolver) error { var serviceErrs []error protoFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool { - for i := 0; i < fd.Services().Len(); i++ { + for i := range fd.Services().Len() { sd := fd.Services().Get(i) if sd.Name() == "Msg" { // We use the heuristic that services name Msg are exactly the diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 84a2980b72..eb287b1ef7 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -19,12 +19,12 @@ var addr1 = sdk.AccAddress([]byte("addr1")) func (s *paginationTestSuite) TestFilteredPaginations() { var balances sdk.Coins - for i := 0; i < numBalances; i++ { + for i := range numBalances { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } - for i := 0; i < 4; i++ { + for i := range 4 { denom := fmt.Sprintf("test%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 250)) } @@ -92,12 +92,12 @@ func (s *paginationTestSuite) TestFilteredPaginations() { func (s *paginationTestSuite) TestReverseFilteredPaginations() { var balances sdk.Coins - for i := 0; i < numBalances; i++ { + for i := range numBalances { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } - for i := 0; i < 10; i++ { + for i := range 10 { denom := fmt.Sprintf("test%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 250)) } @@ -170,12 +170,12 @@ func (s *paginationTestSuite) TestReverseFilteredPaginations() { func (s *paginationTestSuite) TestFilteredPaginate() { var balances sdk.Coins - for i := 0; i < numBalances; i++ { + for i := range numBalances { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } - for i := 0; i < 5; i++ { + for i := range 5 { denom := fmt.Sprintf("test%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 250)) } diff --git a/types/query/fuzz_test.go b/types/query/fuzz_test.go index 8df5f1a020..60d50281c3 100644 --- a/types/query/fuzz_test.go +++ b/types/query/fuzz_test.go @@ -40,7 +40,7 @@ func FuzzPagination(f *testing.F) { } // 1.5. Use the inprocess fuzzer to mutate variables. - for i := 0; i < 1000; i++ { + for range 1000 { qr := new(query.PageRequest) gf.Fuzz(qr) seeds = append(seeds, qr) @@ -57,7 +57,7 @@ func FuzzPagination(f *testing.F) { // 3. Setup the keystore. var balances sdk.Coins - for i := 0; i < 5; i++ { + for i := range 5 { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, int64(100+i))) } diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index 068ddce1cd..b0b94e93e5 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -112,7 +112,7 @@ func (s *paginationTestSuite) TestPagination() { var balances sdk.Coins - for i := 0; i < numBalances; i++ { + for i := range numBalances { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } @@ -220,7 +220,7 @@ func (s *paginationTestSuite) TestReversePagination() { var balances sdk.Coins - for i := 0; i < numBalances; i++ { + for i := range numBalances { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } @@ -339,7 +339,7 @@ func (s *paginationTestSuite) TestReversePagination() { func (s *paginationTestSuite) TestPaginate() { var balances sdk.Coins - for i := 0; i < 2; i++ { + for i := range 2 { denom := fmt.Sprintf("foo%ddenom", i) balances = append(balances, sdk.NewInt64Coin(denom, 100)) } diff --git a/types/simulation/types.go b/types/simulation/types.go index 32bcd54520..0660c87b66 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -157,7 +157,7 @@ type AppParams map[string]json.RawMessage // object. If it exists, it'll be decoded and returned. Otherwise, the provided // ParamSimulator is used to generate a random value or default value (eg: in the // case of operation weights where Rand is not used). -func (sp AppParams) GetOrGenerate(key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) { +func (sp AppParams) GetOrGenerate(key string, ptr any, r *rand.Rand, ps ParamSimulator) { if v, ok := sp[key]; ok && v != nil { err := json.Unmarshal(v, ptr) if err != nil { diff --git a/types/tx/ext.go b/types/tx/ext.go index fb2e1ed448..29b996eea6 100644 --- a/types/tx/ext.go +++ b/types/tx/ext.go @@ -5,7 +5,7 @@ import ( ) // TxExtensionOptionI defines the interface for tx extension options -type TxExtensionOptionI interface{} +type TxExtensionOptionI any // unpackTxExtensionOptionsI unpacks Any's to TxExtensionOptionI's. func unpackTxExtensionOptionsI(unpacker types.AnyUnpacker, anys []*types.Any) error { diff --git a/types/tx/msgs.go b/types/tx/msgs.go index 25e79c4457..16f0ed1f9f 100644 --- a/types/tx/msgs.go +++ b/types/tx/msgs.go @@ -14,7 +14,7 @@ const ( // MsgResponse is the interface all Msg server handlers' response types need to // implement. It's the interface that's representing all Msg responses packed // in Anys. -type MsgResponse interface{} +type MsgResponse any // SetMsgs takes a slice of sdk.Msg's and turn them into Any's. func SetMsgs(msgs []sdk.Msg) ([]*types.Any, error) { diff --git a/types/utils.go b/types/utils.go index b912be36f4..d7612d7302 100644 --- a/types/utils.go +++ b/types/utils.go @@ -18,7 +18,7 @@ import ( // If the passed JSON isn't valid it will return an error. // Deprecated: SortJSON was used for GetSignbytes, this is now automatic with amino signing func SortJSON(toSortJSON []byte) ([]byte, error) { - var c interface{} + var c any err := json.Unmarshal(toSortJSON, &c) if err != nil { return nil, err diff --git a/types/utils_test.go b/types/utils_test.go index 1b0c3f0857..dbbb5ec261 100644 --- a/types/utils_test.go +++ b/types/utils_test.go @@ -2,6 +2,7 @@ package types_test import ( "bytes" + "slices" "testing" "time" @@ -134,7 +135,7 @@ func (s *utilsTestSuite) TestAppendParseBytes() { testByte2 := []byte(test2) combinedBytes := sdk.AppendLengthPrefixedBytes(address.MustLengthPrefix(testByte1), address.MustLengthPrefix(testByte2)) - testCombineBytes := append([]byte{}, address.MustLengthPrefix(testByte1)...) + testCombineBytes := slices.Clone(address.MustLengthPrefix(testByte1)) testCombineBytes = append(testCombineBytes, address.MustLengthPrefix(testByte2)...) s.Require().Equal(combinedBytes, testCombineBytes) diff --git a/version/version.go b/version/version.go index 8f1f040d47..13e80d4924 100644 --- a/version/version.go +++ b/version/version.go @@ -122,5 +122,5 @@ func (d buildDep) String() string { return fmt.Sprintf("%s@%s", d.Path, d.Version) } -func (d buildDep) MarshalJSON() ([]byte, error) { return json.Marshal(d.String()) } -func (d buildDep) MarshalYAML() (interface{}, error) { return d.String(), nil } +func (d buildDep) MarshalJSON() ([]byte, error) { return json.Marshal(d.String()) } +func (d buildDep) MarshalYAML() (any, error) { return d.String(), nil } diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 0f3b89e600..b9c46ab942 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -1195,7 +1195,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []cryptotypes.PubKey, signatures [][]byte) { pubkeys = make([]cryptotypes.PubKey, n) signatures = make([][]byte, n) - for i := 0; i < n; i++ { + for i := range n { var privkey cryptotypes.PrivKey = secp256k1.GenPrivKey() // TODO: also generate ed25519 keys as below when ed25519 keys are @@ -1232,7 +1232,7 @@ func expectedGasCostByKeys(pubkeys []cryptotypes.PubKey) uint64 { func TestCountSubkeys(t *testing.T) { genPubKeys := func(n int) []cryptotypes.PubKey { var ret []cryptotypes.PubKey - for i := 0; i < n; i++ { + for range n { ret = append(ret, secp256k1.GenPrivKey().PubKey()) } return ret @@ -1274,7 +1274,7 @@ func TestAnteHandlerSigLimitExceeded(t *testing.T) { addrs []sdk.AccAddress privs []cryptotypes.PrivKey ) - for i := 0; i < 8; i++ { + for i := range 8 { addrs = append(addrs, accs[i].acc.GetAddress()) privs = append(privs, accs[i].priv) } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index f995811eec..8eb087c554 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -472,7 +472,7 @@ func ConsumeMultisignatureVerificationGas( size := sig.BitArray.Count() sigIndex := 0 - for i := 0; i < size; i++ { + for i := range size { if !sig.BitArray.GetIndex(i) { continue } diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index 41b3080510..5d56d3ca81 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -83,7 +83,7 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { multisigKey1 := kmultisig.NewLegacyAminoPubKey(2, pkSet1) multisignature1 := multisig.NewMultisig(len(pkSet1)) expectedCost1 := expectedGasCostByKeys(pkSet1) - for i := 0; i < len(pkSet1); i++ { + for i := range pkSet1 { stdSig := legacytx.StdSignature{PubKey: pkSet1[i], Signature: sigSet1[i]} //nolint:staticcheck // SA1019: legacytx.StdSignature is deprecated sigV2, err := legacytx.StdSignatureToSignatureV2(suite.clientCtx.LegacyAmino, stdSig) require.NoError(t, err) diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index 58fca4832c..93376714d0 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -117,7 +117,7 @@ func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { func (suite *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { var accounts []TestAccount - for i := 0; i < numAccs; i++ { + for i := range numAccs { priv, _, addr := testdata.KeyTestPubAddr() acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, addr) err := acc.SetAccountNumber(uint64(i + 1000)) diff --git a/x/auth/keeper/deterministic_test.go b/x/auth/keeper/deterministic_test.go index 879b2e0bc9..7cd1d5d749 100644 --- a/x/auth/keeper/deterministic_test.go +++ b/x/auth/keeper/deterministic_test.go @@ -106,7 +106,7 @@ func (suite *DeterministicTestSuite) createAndSetAccounts(t *rapid.T, count int) accNums[i] += lane * 1000 } - for i := 0; i < count; i++ { + for i := range count { pub := pubkeyGenerator(t).Draw(t, "pubkey") addr := sdk.AccAddress(pub.Address()) accNum := accNums[i] @@ -154,7 +154,7 @@ func (suite *DeterministicTestSuite) TestGRPCQueryAccounts() { req := &types.QueryAccountsRequest{Pagination: testdata.PaginationGenerator(t, uint64(numAccs)).Draw(t, "accounts")} testdata.DeterministicIterations(suite.ctx, suite.T(), req, suite.queryClient.Accounts, 0, true) - for i := 0; i < numAccs; i++ { + for i := range numAccs { suite.accountKeeper.RemoveAccount(suite.ctx, accs[i]) } }) @@ -270,12 +270,12 @@ func (suite *DeterministicTestSuite) TestGRPCQueryModuleAccounts() { maccsCount := rapid.IntRange(1, 10).Draw(t, "accounts") maccs := make([]string, maccsCount) - for i := 0; i < maccsCount; i++ { + for i := range maccsCount { maccs[i] = rapid.StringMatching(`[a-z]{5,}`).Draw(t, "module-name") } maccPerms := make(map[string][]string) - for i := 0; i < maccsCount; i++ { + for i := range maccsCount { mPerms := make([]string, 0, 4) for _, permission := range permissions { if rapid.Bool().Draw(t, "permissions") { diff --git a/x/auth/migrations/legacytx/amino_signing.go b/x/auth/migrations/legacytx/amino_signing.go index 851366aa9b..a65ad3d2ca 100644 --- a/x/auth/migrations/legacytx/amino_signing.go +++ b/x/auth/migrations/legacytx/amino_signing.go @@ -39,7 +39,7 @@ func MultiSignatureDataToAminoMultisignature(cdc *codec.LegacyAmino, mSig *signi n := len(mSig.Signatures) sigs := make([][]byte, n) - for i := 0; i < n; i++ { + for i := range n { var err error sigs[i], err = SignatureDataToAminoSignature(cdc, mSig.Signatures[i]) if err != nil { diff --git a/x/auth/migrations/legacytx/stdsign.go b/x/auth/migrations/legacytx/stdsign.go index dfd83a4f11..b343abcc8f 100644 --- a/x/auth/migrations/legacytx/stdsign.go +++ b/x/auth/migrations/legacytx/stdsign.go @@ -109,7 +109,7 @@ func (ss StdSignature) GetPubKey() cryptotypes.PubKey { } // MarshalYAML returns the YAML representation of the signature. -func (ss StdSignature) MarshalYAML() (interface{}, error) { +func (ss StdSignature) MarshalYAML() (any, error) { pk := "" if ss.PubKey != nil { pk = ss.String() @@ -168,7 +168,7 @@ func pubKeySigToSigData(cdc *codec.LegacyAmino, key cryptotypes.PubKey, sig []by n := multiSig.BitArray.Count() signatures := multisig.NewMultisig(n) sigIdx := 0 - for i := 0; i < n; i++ { + for i := range n { if bitArray.GetIndex(i) { data, err := pubKeySigToSigData(cdc, pubKeys[i], multiSig.Sigs[sigIdx]) if err != nil { diff --git a/x/auth/migrations/legacytx/stdtx_builder.go b/x/auth/migrations/legacytx/stdtx_builder.go index 88bfe11575..0aba7916a2 100644 --- a/x/auth/migrations/legacytx/stdtx_builder.go +++ b/x/auth/migrations/legacytx/stdtx_builder.go @@ -136,7 +136,7 @@ func SignatureV2ToStdSignature(cdc *codec.LegacyAmino, sig signing.SignatureV2) } // Unmarshaler is a generic type for Unmarshal functions -type Unmarshaler func(bytes []byte, ptr interface{}) error +type Unmarshaler func(bytes []byte, ptr any) error // DefaultTxEncoder logic for standard transaction encoding func DefaultTxEncoder(cdc *codec.LegacyAmino) sdk.TxEncoder { diff --git a/x/auth/tx/encode_decode_test.go b/x/auth/tx/encode_decode_test.go index 820d513646..6919bdfa66 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "math" + "slices" "testing" "github.com/stretchr/testify/require" @@ -189,14 +190,14 @@ func TestRejectNonADR027(t *testing.T) { // // Consume "BodyBytes" field. _, _, m := protowire.ConsumeField(txBz) - bodyBz = append([]byte{}, txBz[:m]...) + bodyBz = slices.Clone(txBz[:m]) txBz = txBz[m:] // Skip over "BodyBytes" bytes. // Consume "AuthInfoBytes" field. _, _, m = protowire.ConsumeField(txBz) - authInfoBz = append([]byte{}, txBz[:m]...) + authInfoBz = slices.Clone(txBz[:m]) txBz = txBz[m:] // Skip over "AuthInfoBytes" bytes. // Consume "Signature" field, it's the remaining bytes. - sigsBz := append([]byte{}, txBz...) + sigsBz := slices.Clone(txBz) // bodyBz's length prefix is 5, with `5` as varint encoding. We also try a // longer varint encoding for 5: `133 00`. diff --git a/x/auth/types/params.go b/x/auth/types/params.go index b157eb220e..aba8a6ccc4 100644 --- a/x/auth/types/params.go +++ b/x/auth/types/params.go @@ -47,7 +47,7 @@ func (p Params) SigVerifyCostSecp256r1() uint64 { return p.SigVerifyCostSecp256k1 / 2 } -func validateTxSigLimit(i interface{}) error { +func validateTxSigLimit(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -60,7 +60,7 @@ func validateTxSigLimit(i interface{}) error { return nil } -func validateSigVerifyCostED25519(i interface{}) error { +func validateSigVerifyCostED25519(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -73,7 +73,7 @@ func validateSigVerifyCostED25519(i interface{}) error { return nil } -func validateSigVerifyCostSecp256k1(i interface{}) error { +func validateSigVerifyCostSecp256k1(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -86,7 +86,7 @@ func validateSigVerifyCostSecp256k1(i interface{}) error { return nil } -func validateMaxMemoCharacters(i interface{}) error { +func validateMaxMemoCharacters(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -99,7 +99,7 @@ func validateMaxMemoCharacters(i interface{}) error { return nil } -func validateTxSizeCostPerByte(i interface{}) error { +func validateTxSizeCostPerByte(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 78151eaa3d..a5abd432f6 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -106,7 +106,7 @@ Examples: } // check for duplicates - for i := 0; i < len(allowList); i++ { + for i := range allowList { for j := i + 1; j < len(allowList); j++ { if allowList[i] == allowList[j] { return fmt.Errorf("duplicate address %s in allow-list", allowList[i]) diff --git a/x/authz/simulation/genesis.go b/x/authz/simulation/genesis.go index 8dfaf7ed18..de3ef60b93 100644 --- a/x/authz/simulation/genesis.go +++ b/x/authz/simulation/genesis.go @@ -18,7 +18,7 @@ import ( // genGrant returns a slice of authorization grants. func genGrant(r *rand.Rand, accounts []simtypes.Account, genT time.Time) []authz.GrantAuthorization { authorizations := make([]authz.GrantAuthorization, len(accounts)-1) - for i := 0; i < len(accounts)-1; i++ { + for i := range len(accounts) - 1 { granter := accounts[i] grantee := accounts[i+1] var expiration *time.Time diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index 1e3121d633..908ffa91f1 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -34,7 +34,7 @@ func genSequenceOfTxs(txGen client.TxConfig, var err error txs := make([]sdk.Tx, numToGenerate) - for i := 0; i < numToGenerate; i++ { + for i := range numToGenerate { txs[i], err = simtestutil.GenSignedMockTx( rand.New(rand.NewSource(time.Now().UnixNano())), txGen, @@ -50,7 +50,7 @@ func genSequenceOfTxs(txGen client.TxConfig, break } - for i := 0; i < len(initSeqNums); i++ { + for i := range initSeqNums { initSeqNums[i]++ } } diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 10a1c67e84..51650ce420 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -591,7 +591,7 @@ func (suite *KeeperTestSuite) TestGRPCDenomOwners() { suite.mockMintCoins(mintAcc) suite.Require().NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins)) - for i := 0; i < 10; i++ { + for i := range 10 { addr := sdk.AccAddress(fmt.Sprintf("account-%d", i)) bal := sdk.NewCoins(sdk.NewCoin( @@ -816,7 +816,7 @@ func (suite *KeeperTestSuite) TestGRPCDenomOwnersByQuery() { suite.mockMintCoins(mintAcc) suite.Require().NoError(keeper.MintCoins(ctx, minttypes.ModuleName, newCoins)) - for i := 0; i < 10; i++ { + for i := range 10 { addr := sdk.AccAddress(fmt.Sprintf("account-%d", i)) bal := sdk.NewCoins(sdk.NewCoin( diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index b1ba26055a..e21d475df3 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -2409,7 +2409,7 @@ func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { *ps.(*banktypes.Params) = ms.ps } -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr interface{}) {} +func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) {} func (suite *KeeperTestSuite) TestMigrator_Migrate3to4() { bankKeeper := suite.bankKeeper diff --git a/x/bank/migrations/v2/json_test.go b/x/bank/migrations/v2/json_test.go index 99984fb9c9..09caa926f2 100644 --- a/x/bank/migrations/v2/json_test.go +++ b/x/bank/migrations/v2/json_test.go @@ -49,7 +49,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go index ae6c54c56c..3fb5fc7a6f 100644 --- a/x/bank/migrations/v3/store_test.go +++ b/x/bank/migrations/v3/store_test.go @@ -1,6 +1,7 @@ package v3_test import ( + "slices" "testing" "github.com/stretchr/testify/require" @@ -26,7 +27,7 @@ func TestMigrateStore(t *testing.T) { ctx := testutil.DefaultContext(bankKey, storetypes.NewTransientStoreKey("transient_test")) store := runtime.KVStoreAdapter(storeService.OpenKVStore(ctx)) - addr := sdk.AccAddress([]byte("addr________________")) + addr := sdk.AccAddress("addr________________") prefixAccStore := prefix.NewStore(store, v2.CreateAccountBalancesPrefix(addr)) balances := sdk.NewCoins( @@ -94,7 +95,7 @@ func TestMigrateDenomMetaData(t *testing.T) { for i := range []int{0, 1} { // keys before 0.45 had denom two times in the key - key := append([]byte{}, []byte(metaData[i].Base)...) + key := slices.Clone([]byte(metaData[i].Base)) key = append(key, []byte(metaData[i].Base)...) bz, err := encCfg.Codec.Marshal(&metaData[i]) require.NoError(t, err) diff --git a/x/bank/migrations/v4/store_test.go b/x/bank/migrations/v4/store_test.go index 6bc199f056..911a9b0207 100644 --- a/x/bank/migrations/v4/store_test.go +++ b/x/bank/migrations/v4/store_test.go @@ -29,7 +29,7 @@ func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { *ps.(*types.Params) = ms.ps } -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr interface{}) {} +func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) {} func TestMigrate(t *testing.T) { encCfg := moduletestutil.MakeTestEncodingConfig(bank.AppModuleBasic{}) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index c5be578e47..7aac725290 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -352,7 +352,7 @@ func sendMsgMultiSend( ) error { accountNumbers := make([]uint64, len(msg.Inputs)) sequenceNumbers := make([]uint64, len(msg.Inputs)) - for i := 0; i < len(msg.Inputs); i++ { + for i := range msg.Inputs { addr, err := ak.AddressCodec().StringToBytes(msg.Inputs[i].Address) if err != nil { panic(err) @@ -433,7 +433,7 @@ func randomSendFields( func getModuleAccounts(ak types.AccountKeeper, ctx sdk.Context, moduleAccCount int) []simtypes.Account { moduleAccounts := make([]simtypes.Account, moduleAccCount) - for i := 0; i < moduleAccCount; i++ { + for i := range moduleAccCount { acc := ak.GetModuleAccount(ctx, disttypes.ModuleName) mAcc := simtypes.Account{ Address: acc.GetAddress(), diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index c48fb01f42..2ac676988e 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -157,7 +157,7 @@ func TestSanitizeBalances(t *testing.T) { // 3. Compare and ensure that all the values are sorted in ascending order. // Invariant after sorting: // a[i] <= a[i+1...n] - for i := 0; i < len(sorted); i++ { + for i := range sorted { ai := sorted[i] // Ensure that every single value that comes after i is less than it. for j := i + 1; j < len(sorted); j++ { @@ -170,7 +170,7 @@ func TestSanitizeBalances(t *testing.T) { } func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.AccAddress, pkL []*ed25519.PubKey) { - for i := 0; i < n; i++ { + for range n { pk := ed25519.GenPrivKey().PubKey().(*ed25519.PubKey) pkL = append(pkL, pk) accL = append(accL, sdk.AccAddress(pk.Address())) @@ -178,7 +178,7 @@ func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.AccAddress, pkL []*ed25 return accL, pkL } -var sink, revert interface{} +var sink, revert any func BenchmarkSanitizeBalances500(b *testing.B) { benchmarkSanitizeBalances(b, 500) diff --git a/x/bank/types/params.go b/x/bank/types/params.go index 106bc890a0..287433857c 100644 --- a/x/bank/types/params.go +++ b/x/bank/types/params.go @@ -49,7 +49,7 @@ func NewSendEnabled(denom string, sendEnabled bool) *SendEnabled { } // validateIsBool is used by the x/params module to validate that a thing is a bool. -func validateIsBool(i interface{}) error { +func validateIsBool(i any) error { _, ok := i.(bool) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/bank/types/params_legacy.go b/x/bank/types/params_legacy.go index 6f6a25a069..b8f8d183f5 100644 --- a/x/bank/types/params_legacy.go +++ b/x/bank/types/params_legacy.go @@ -39,7 +39,7 @@ func GetSendEnabledParams(ctx sdk.Context, legacySubspace exported.Subspace) []* return sendEnabled } -func validateSendEnabledParams(i interface{}) error { +func validateSendEnabledParams(i any) error { params, ok := i.([]*SendEnabled) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -58,7 +58,7 @@ func validateSendEnabledParams(i interface{}) error { return nil } -func validateSendEnabled(i interface{}) error { +func validateSendEnabled(i any) error { param, ok := i.(SendEnabled) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/bank/types/send_authorization.go b/x/bank/types/send_authorization.go index 2244930170..d0357c6c21 100644 --- a/x/bank/types/send_authorization.go +++ b/x/bank/types/send_authorization.go @@ -73,7 +73,7 @@ func (a SendAuthorization) ValidateBasic() error { } found := make(map[string]bool, 0) - for i := 0; i < len(a.AllowList); i++ { + for i := range a.AllowList { if found[a.AllowList[i]] { return ErrDuplicateEntry } diff --git a/x/consensus/exported/exported.go b/x/consensus/exported/exported.go index 60dd19abb4..6c2135f712 100644 --- a/x/consensus/exported/exported.go +++ b/x/consensus/exported/exported.go @@ -14,7 +14,7 @@ type ( // // NOTE: This is used solely for migration of x/params managed parameters. ParamStore interface { - Get(ctx sdk.Context, key []byte, ptr interface{}) + Get(ctx sdk.Context, key []byte, ptr any) } // ConsensusParamSetter defines the interface fulfilled by BaseApp's diff --git a/x/crisis/exported/exported.go b/x/crisis/exported/exported.go index 8b43ec74fc..43772091f6 100644 --- a/x/crisis/exported/exported.go +++ b/x/crisis/exported/exported.go @@ -13,6 +13,6 @@ type ( // // NOTE: This is used solely for migration of x/params managed parameters. Subspace interface { - Get(ctx sdk.Context, key []byte, ptr interface{}) + Get(ctx sdk.Context, key []byte, ptr any) } ) diff --git a/x/crisis/migrations/v2/migrate_test.go b/x/crisis/migrations/v2/migrate_test.go index c1dddc05a5..b393689421 100644 --- a/x/crisis/migrations/v2/migrate_test.go +++ b/x/crisis/migrations/v2/migrate_test.go @@ -24,7 +24,7 @@ func newMockSubspace(fee sdk.Coin) mockSubspace { return mockSubspace{constantFee: fee} } -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { +func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) { *ptr.(*sdk.Coin) = ms.constantFee } diff --git a/x/crisis/types/legacy_params.go b/x/crisis/types/legacy_params.go index bcb689a4fa..5aae3e252e 100644 --- a/x/crisis/types/legacy_params.go +++ b/x/crisis/types/legacy_params.go @@ -17,7 +17,7 @@ func ParamKeyTable() paramtypes.KeyTable { ) } -func validateConstantFee(i interface{}) error { +func validateConstantFee(i any) error { v, ok := i.(sdk.Coin) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/distribution/migrations/v3/json_test.go b/x/distribution/migrations/v3/json_test.go index 8fba6cf9ee..399b26f8d7 100644 --- a/x/distribution/migrations/v3/json_test.go +++ b/x/distribution/migrations/v3/json_test.go @@ -35,7 +35,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/distribution/types/params.go b/x/distribution/types/params.go index f7c9802841..cbeab91651 100644 --- a/x/distribution/types/params.go +++ b/x/distribution/types/params.go @@ -21,7 +21,7 @@ func (p Params) ValidateBasic() error { return validateCommunityTax(p.CommunityTax) } -func validateCommunityTax(i interface{}) error { +func validateCommunityTax(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -40,7 +40,7 @@ func validateCommunityTax(i interface{}) error { return nil } -func validateWithdrawAddrEnabled(i interface{}) error { +func validateWithdrawAddrEnabled(i any) error { _, ok := i.(bool) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go index 21bfd0f1bf..6f03705cb6 100644 --- a/x/distribution/types/params_internal_test.go +++ b/x/distribution/types/params_internal_test.go @@ -10,7 +10,7 @@ import ( func Test_validateAuxFuncs(t *testing.T) { type args struct { - i interface{} + i any } tests := []struct { name string diff --git a/x/epochs/keeper/genesis_test.go b/x/epochs/keeper/genesis_test.go index 55175ae7d1..26cd6fea23 100644 --- a/x/epochs/keeper/genesis_test.go +++ b/x/epochs/keeper/genesis_test.go @@ -20,7 +20,7 @@ func TestEpochsExportGenesis(t *testing.T) { require.Len(t, genesis.Epochs, 4) expectedEpochs := types.DefaultGenesis().Epochs - for i := 0; i < len(expectedEpochs); i++ { + for i := range expectedEpochs { expectedEpochs[i].CurrentEpochStartHeight = chainStartHeight expectedEpochs[i].StartTime = chainStartTime } diff --git a/x/epochs/simulation/genesis.go b/x/epochs/simulation/genesis.go index fc5d1f77cc..e8fc9658c8 100644 --- a/x/epochs/simulation/genesis.go +++ b/x/epochs/simulation/genesis.go @@ -18,7 +18,7 @@ func RandomizedEpochs(r *rand.Rand) []types.EpochInfo { // Gen max 10 epoch n := r.Intn(11) var epochs []types.EpochInfo - for i := 0; i < n; i++ { + for i := range n { identifier := "identifier-" + strconv.Itoa(i) duration := GenDuration(r) epoch := types.NewGenesisEpochInfo(identifier, duration) diff --git a/x/epochs/types/hooks_test.go b/x/epochs/types/hooks_test.go index c2b460aae7..2c6543ea58 100644 --- a/x/epochs/types/hooks_test.go +++ b/x/epochs/types/hooks_test.go @@ -76,7 +76,7 @@ func (s *KeeperTestSuite) TestHooksPanicRecovery() { } for tcIndex, tc := range tests { - for epochActionSelector := 0; epochActionSelector < 2; epochActionSelector++ { + for epochActionSelector := range 2 { s.SetupTest() hookRefs := []types.EpochHooks{} @@ -103,7 +103,7 @@ func (s *KeeperTestSuite) TestHooksPanicRecovery() { } } - for i := 0; i < len(hooks); i++ { + for i := range hooks { epochHook := hookRefs[i].(*dummyEpochHook) s.Require().Equal(tc.expectedCounterValues[i], epochHook.successCounter, "test case index %d", tcIndex) } diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index d4a564fd9e..05ec1a5f58 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -675,7 +675,7 @@ func createValidators(t *testing.T, stakingMsgSvr stakingtypes.MsgServer, ctx sd require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") - for i := 0; i < len(addrs); i++ { + for i := range addrs { valTokens := sdk.TokensFromConsensusPower(powerAmt[i], sdk.DefaultPowerReduction) valCreateMsg, err := stakingtypes.NewMsgCreateValidator( addrs[i].String(), pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), diff --git a/x/gov/client/cli/prompt.go b/x/gov/client/cli/prompt.go index 1722c53e2e..10bc8b75b2 100644 --- a/x/gov/client/cli/prompt.go +++ b/x/gov/client/cli/prompt.go @@ -62,7 +62,7 @@ func Prompt[T any](data T, namePrefix string) (T, error) { } } - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { // if the field is a struct skip or not slice of string or int then skip switch v.Field(i).Kind() { case reflect.Struct: diff --git a/x/gov/exported/exported.go b/x/gov/exported/exported.go index 08a5d2594e..5de7e5cba8 100644 --- a/x/gov/exported/exported.go +++ b/x/gov/exported/exported.go @@ -13,6 +13,6 @@ type ( // // NOTE: This is used solely for migration of x/params managed parameters. ParamSubspace interface { - Get(ctx sdk.Context, key []byte, ptr interface{}) + Get(ctx sdk.Context, key []byte, ptr any) } ) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index ef6da81eb9..2ccc09954c 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -375,7 +375,7 @@ func TestChargeDeposit(t *testing.T) { } for _, tc := range testCases { - for i := 0; i < 3; i++ { + for i := range 3 { testName := func(i int) string { switch i { case 0: diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index 3bceea9951..9a5d6bacc6 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -211,7 +211,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { "request proposals with limit 3", func() { // create 5 test proposals - for i := 0; i < 5; i++ { + for i := range 5 { govAddress := suite.govKeeper.GetGovernanceAccount(suite.ctx).GetAddress() testProposal := []sdk.Msg{ v1.NewMsgVote(govAddress, uint64(i), v1.OptionYes, ""), @@ -313,7 +313,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { } var proposals []*v1.Proposal - for i := 0; i < len(testProposals); i++ { + for i := range testProposals { if testProposals[i].GetStatus() == v1.StatusVotingPeriod { proposals = append(proposals, testProposals[i]) } @@ -333,7 +333,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { } var proposals []*v1.Proposal - for i := 0; i < len(testProposals); i++ { + for i := range testProposals { if testProposals[i].GetStatus() == v1.StatusDepositPeriod { proposals = append(proposals, testProposals[i]) } @@ -381,7 +381,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { suite.Require().NoError(err) suite.Require().Len(proposals.GetProposals(), len(expRes.GetProposals())) - for i := 0; i < len(proposals.GetProposals()); i++ { + for i := range proposals.GetProposals() { suite.Require().NoError(err) suite.Require().NotEmpty(proposals.GetProposals()[i]) suite.Require().Equal(expRes.GetProposals()[i].String(), proposals.GetProposals()[i].String()) diff --git a/x/gov/migrations/v2/json_test.go b/x/gov/migrations/v2/json_test.go index 9203bf0149..fb26e080e0 100644 --- a/x/gov/migrations/v2/json_test.go +++ b/x/gov/migrations/v2/json_test.go @@ -38,7 +38,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/gov/migrations/v3/json_test.go b/x/gov/migrations/v3/json_test.go index a9089cf686..177e3c6fa3 100644 --- a/x/gov/migrations/v3/json_test.go +++ b/x/gov/migrations/v3/json_test.go @@ -66,7 +66,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/gov/migrations/v4/json_test.go b/x/gov/migrations/v4/json_test.go index 18ef6dba37..cc9a2fa8eb 100644 --- a/x/gov/migrations/v4/json_test.go +++ b/x/gov/migrations/v4/json_test.go @@ -48,7 +48,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/gov/migrations/v4/store_test.go b/x/gov/migrations/v4/store_test.go index 0704896ac4..059e40b289 100644 --- a/x/gov/migrations/v4/store_test.go +++ b/x/gov/migrations/v4/store_test.go @@ -54,7 +54,7 @@ func newMockSubspace(p v1.Params) mockSubspace { } } -func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { +func (ms mockSubspace) Get(ctx sdk.Context, key []byte, ptr any) { switch string(key) { case string(v1.ParamStoreKeyDepositParams): *ptr.(*v1.DepositParams) = ms.dp diff --git a/x/gov/simulation/msg_factory.go b/x/gov/simulation/msg_factory.go index 65a99b1e5f..d14f2cde32 100644 --- a/x/gov/simulation/msg_factory.go +++ b/x/gov/simulation/msg_factory.go @@ -211,7 +211,7 @@ func submitProposalWithVotesScheduled( // future ops so that votes do not flood the sims. if r.Intn(100) == 1 { // 1% chance now := simsx.BlockTime(ctx) - for i := 0; i < numVotes; i++ { + for i := range numVotes { var vF simsx.SimMsgFactoryFn[*v1.MsgVote] = func(ctx context.Context, testData *simsx.ChainDataSource, reporter simsx.SimulationReporter) ([]simsx.SimAccount, *v1.MsgVote) { switch p, err := k.Proposals.Get(ctx, proposalID); { case err != nil: diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index a0cace28f7..c1d3f749c6 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -294,7 +294,7 @@ func simulateMsgSubmitProposal( votingPeriod := params.VotingPeriod s := NewSharedState() fops := make([]simtypes.FutureOperation, numVotes+1) - for i := 0; i < numVotes; i++ { + for i := range numVotes { whenVote := ctx.BlockHeader().Time.Add(time.Duration(r.Int63n(int64(votingPeriod.Seconds()))) * time.Second) fops[i] = simtypes.FutureOperation{ BlockTime: whenVote, diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index ba8c7b0335..7f9c441c43 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -75,7 +75,7 @@ func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn func mockWeightedProposalMsg(n int) []simtypes.WeightedProposalMsg { wpc := make([]simtypes.WeightedProposalMsg, n) - for i := 0; i < n; i++ { + for i := range n { wpc[i] = MockWeightedProposals{i} } return wpc @@ -84,7 +84,7 @@ func mockWeightedProposalMsg(n int) []simtypes.WeightedProposalMsg { // nolint // keeping this legacy proposal for testing func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { wpc := make([]simtypes.WeightedProposalContent, n) - for i := 0; i < n; i++ { + for i := range n { wpc[i] = MockWeightedProposals{i} } return wpc diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index e27e9b57aa..74ec881ec1 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -12,8 +12,8 @@ import ( // ParamSubspace defines the expected Subspace interface for parameters (noalias) type ParamSubspace interface { - Get(ctx sdk.Context, key []byte, ptr interface{}) - Set(ctx sdk.Context, key []byte, param interface{}) + Get(ctx sdk.Context, key []byte, ptr any) + Set(ctx sdk.Context, key []byte, param any) } // StakingKeeper expected staking keeper (Validator and Delegator sets) (noalias) diff --git a/x/gov/types/v1/params_legacy.go b/x/gov/types/v1/params_legacy.go index ceee66b235..522bda56eb 100644 --- a/x/gov/types/v1/params_legacy.go +++ b/x/gov/types/v1/params_legacy.go @@ -26,7 +26,7 @@ func ParamKeyTable() paramtypes.KeyTable { ) } -func validateDepositParams(i interface{}) error { +func validateDepositParams(i any) error { v, ok := i.(DepositParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -42,7 +42,7 @@ func validateDepositParams(i interface{}) error { return nil } -func validateTallyParams(i interface{}) error { +func validateTallyParams(i any) error { v, ok := i.(TallyParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -84,7 +84,7 @@ func validateTallyParams(i interface{}) error { return nil } -func validateVotingParams(i interface{}) error { +func validateVotingParams(i any) error { v, ok := i.(VotingParams) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/group/client/cli/tx_test.go b/x/group/client/cli/tx_test.go index 9def6aa675..377c1c6d35 100644 --- a/x/group/client/cli/tx_test.go +++ b/x/group/client/cli/tx_test.go @@ -241,7 +241,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { s.Require().NoError(client.SetCmdClientContextHandler(s.baseCtx, cmd)) groupIDs := make([]string, 2) - for i := 0; i < 2; i++ { + for i := range 2 { validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -1208,7 +1208,7 @@ func (s *CLITestSuite) TestTxVote() { cmd.SetOut(io.Discard) ids := make([]string, 4) - for i := 0; i < len(ids); i++ { + for i := range ids { ids[i] = fmt.Sprint(i + 1) } diff --git a/x/group/internal/orm/auto_uint64.go b/x/group/internal/orm/auto_uint64.go index b3b6d22fc7..202d132995 100644 --- a/x/group/internal/orm/auto_uint64.go +++ b/x/group/internal/orm/auto_uint64.go @@ -132,7 +132,7 @@ func (a AutoUInt64Table) Export(store storetypes.KVStore, dest ModelSlicePtr) (u // Import clears the table and initializes it from the given data interface{}. // data should be a slice of structs that implement PrimaryKeyed. -func (a AutoUInt64Table) Import(store storetypes.KVStore, data interface{}, seqValue uint64) error { +func (a AutoUInt64Table) Import(store storetypes.KVStore, data any, seqValue uint64) error { if err := a.seq.InitVal(store, seqValue); err != nil { return errors.Wrap(err, "sequence") } diff --git a/x/group/internal/orm/example_test.go b/x/group/internal/orm/example_test.go index 4cc422e02d..c99cd5db60 100644 --- a/x/group/internal/orm/example_test.go +++ b/x/group/internal/orm/example_test.go @@ -32,8 +32,8 @@ func NewTestKeeper(cdc codec.Codec) TestKeeper { if err != nil { panic(err.Error()) } - k.autoUInt64TableModelByMetadataIndex, err = NewIndex(k.autoUInt64Table, AutoUInt64TableModelByMetadataPrefix, func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Metadata}, nil + k.autoUInt64TableModelByMetadataIndex, err = NewIndex(k.autoUInt64Table, AutoUInt64TableModelByMetadataPrefix, func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Metadata}, nil }, testdata.TableModel{}.Metadata) if err != nil { panic(err.Error()) @@ -43,20 +43,20 @@ func NewTestKeeper(cdc codec.Codec) TestKeeper { if err != nil { panic(err.Error()) } - k.primaryKeyTableModelByNameIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByNamePrefix, func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Name}, nil + k.primaryKeyTableModelByNameIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByNamePrefix, func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Name}, nil }, testdata.TableModel{}.Name) if err != nil { panic(err.Error()) } - k.primaryKeyTableModelByNumberIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByNumberPrefix, func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Number}, nil + k.primaryKeyTableModelByNumberIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByNumberPrefix, func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Number}, nil }, testdata.TableModel{}.Number) if err != nil { panic(err.Error()) } - k.primaryKeyTableModelByMetadataIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByMetadataPrefix, func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Metadata}, nil + k.primaryKeyTableModelByMetadataIndex, err = NewIndex(k.primaryKeyTable, PrimaryKeyTableModelByMetadataPrefix, func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Metadata}, nil }, testdata.TableModel{}.Metadata) if err != nil { panic(err.Error()) diff --git a/x/group/internal/orm/genesis.go b/x/group/internal/orm/genesis.go index 1f9a693e9b..39b4218165 100644 --- a/x/group/internal/orm/genesis.go +++ b/x/group/internal/orm/genesis.go @@ -13,5 +13,5 @@ type TableExportable interface { // interface{}. data should be a slice of structs that implement // PrimaryKeyed. The seqValue is optional and only // used with tables that have an associated sequence. - Import(store storetypes.KVStore, data interface{}, seqValue uint64) error + Import(store storetypes.KVStore, data any, seqValue uint64) error } diff --git a/x/group/internal/orm/index.go b/x/group/internal/orm/index.go index 27bb064af8..d4707a414a 100644 --- a/x/group/internal/orm/index.go +++ b/x/group/internal/orm/index.go @@ -15,9 +15,9 @@ import ( // indexer creates and modifies the second MultiKeyIndex based on the operations and changes on the primary object. type indexer interface { - OnCreate(store types.KVStore, rowID RowID, value interface{}) error - OnDelete(store types.KVStore, rowID RowID, value interface{}) error - OnUpdate(store types.KVStore, rowID RowID, newValue, oldValue interface{}) error + OnCreate(store types.KVStore, rowID RowID, value any) error + OnDelete(store types.KVStore, rowID RowID, value any) error + OnUpdate(store types.KVStore, rowID RowID, newValue, oldValue any) error } var _ Index = &MultiKeyIndex{} @@ -29,13 +29,13 @@ type MultiKeyIndex struct { rowGetter RowGetter indexer indexer indexerFunc IndexerFunc - indexKey interface{} + indexKey any } // NewIndex builds a MultiKeyIndex. // Only single-field indexes are supported and `indexKey` represents such a field value, // which can be []byte, string or uint64. -func NewIndex(tb Indexable, prefix byte, indexerF IndexerFunc, indexKey interface{}) (MultiKeyIndex, error) { +func NewIndex(tb Indexable, prefix byte, indexerF IndexerFunc, indexKey any) (MultiKeyIndex, error) { indexer, err := NewIndexer(indexerF) if err != nil { return MultiKeyIndex{}, err @@ -43,7 +43,7 @@ func NewIndex(tb Indexable, prefix byte, indexerF IndexerFunc, indexKey interfac return newIndex(tb, prefix, indexer, indexer.IndexerFunc(), indexKey) } -func newIndex(tb Indexable, prefix byte, indexer *Indexer, indexerF IndexerFunc, indexKey interface{}) (MultiKeyIndex, error) { +func newIndex(tb Indexable, prefix byte, indexer *Indexer, indexerF IndexerFunc, indexKey any) (MultiKeyIndex, error) { rowGetter := tb.RowGetter() if rowGetter == nil { return MultiKeyIndex{}, errors.ErrORMInvalidArgument.Wrap("rowGetter must not be nil") @@ -72,7 +72,7 @@ func newIndex(tb Indexable, prefix byte, indexer *Indexer, indexerF IndexerFunc, } // Has checks if a key exists. Returns an error on nil key. -func (i MultiKeyIndex) Has(store types.KVStore, key interface{}) (bool, error) { +func (i MultiKeyIndex) Has(store types.KVStore, key any) (bool, error) { pStore := prefix.NewStore(store, []byte{i.prefix}) encodedKey, err := keyPartBytes(key, false) if err != nil { @@ -84,7 +84,7 @@ func (i MultiKeyIndex) Has(store types.KVStore, key interface{}) (bool, error) { } // Get returns a result iterator for the searchKey. Parameters must not be nil. -func (i MultiKeyIndex) Get(store types.KVStore, searchKey interface{}) (Iterator, error) { +func (i MultiKeyIndex) Get(store types.KVStore, searchKey any) (Iterator, error) { pStore := prefix.NewStore(store, []byte{i.prefix}) encodedKey, err := keyPartBytes(searchKey, false) if err != nil { @@ -97,7 +97,7 @@ func (i MultiKeyIndex) Get(store types.KVStore, searchKey interface{}) (Iterator // GetPaginated creates an iterator for the searchKey // starting from pageRequest.Key if provided. // The pageRequest.Key is the rowID while searchKey is a MultiKeyIndex key. -func (i MultiKeyIndex) GetPaginated(store types.KVStore, searchKey interface{}, pageRequest *query.PageRequest) (Iterator, error) { +func (i MultiKeyIndex) GetPaginated(store types.KVStore, searchKey any, pageRequest *query.PageRequest) (Iterator, error) { pStore := prefix.NewStore(store, []byte{i.prefix}) encodedKey, err := keyPartBytes(searchKey, false) if err != nil { @@ -107,7 +107,7 @@ func (i MultiKeyIndex) GetPaginated(store types.KVStore, searchKey interface{}, if pageRequest != nil && len(pageRequest.Key) != 0 { var err error - start, err = buildKeyFromParts([]interface{}{searchKey, pageRequest.Key}) + start, err = buildKeyFromParts([]any{searchKey, pageRequest.Key}) if err != nil { return nil, err } @@ -133,7 +133,7 @@ func (i MultiKeyIndex) GetPaginated(store types.KVStore, searchKey interface{}, // it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. -func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI, endI interface{}) (Iterator, error) { +func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI, endI any) (Iterator, error) { start, end, err := getStartEndBz(startI, endI) if err != nil { return nil, err @@ -153,7 +153,7 @@ func (i MultiKeyIndex) PrefixScan(store types.KVStore, startI, endI interface{}) // this as an endpoint to the public without further limits. See `LimitIterator` // // CONTRACT: No writes may happen within a domain while an iterator exists over it. -func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI, endI interface{}) (Iterator, error) { +func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI, endI any) (Iterator, error) { start, end, err := getStartEndBz(startI, endI) if err != nil { return nil, err @@ -166,7 +166,7 @@ func (i MultiKeyIndex) ReversePrefixScan(store types.KVStore, startI, endI inter // getStartEndBz gets the start and end bytes to be passed into the SDK store // iterator. -func getStartEndBz(startI, endI interface{}) ([]byte, []byte, error) { +func getStartEndBz(startI, endI any) ([]byte, []byte, error) { start, err := getPrefixScanKeyBytes(startI) if err != nil { return nil, nil, err @@ -183,7 +183,7 @@ func getStartEndBz(startI, endI interface{}) ([]byte, []byte, error) { return start, end, nil } -func getPrefixScanKeyBytes(keyI interface{}) ([]byte, error) { +func getPrefixScanKeyBytes(keyI any) ([]byte, error) { var ( key []byte err error @@ -217,7 +217,7 @@ type UniqueIndex struct { } // NewUniqueIndex create a new Index object where duplicate keys are prohibited. -func NewUniqueIndex(tb Indexable, prefix byte, uniqueIndexerFunc UniqueIndexerFunc, indexKey interface{}) (UniqueIndex, error) { +func NewUniqueIndex(tb Indexable, prefix byte, uniqueIndexerFunc UniqueIndexerFunc, indexKey any) (UniqueIndex, error) { uniqueIndexer, err := NewUniqueIndexer(uniqueIndexerFunc) if err != nil { return UniqueIndex{}, err @@ -236,7 +236,7 @@ type indexIterator struct { store types.KVStore rowGetter RowGetter it types.Iterator - indexKey interface{} + indexKey any } // LoadNext loads the next value in the sequence into the pointer passed as dest and returns the key. If there diff --git a/x/group/internal/orm/index_test.go b/x/group/internal/orm/index_test.go index 9b239c6acf..895e82dd80 100644 --- a/x/group/internal/orm/index_test.go +++ b/x/group/internal/orm/index_test.go @@ -32,8 +32,8 @@ func TestNewIndex(t *testing.T) { myTable, err := NewAutoUInt64Table(AutoUInt64TablePrefix, AutoUInt64TableSeqPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) - indexer := func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Metadata}, nil + indexer := func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Metadata}, nil } testCases := []struct { @@ -41,7 +41,7 @@ func TestNewIndex(t *testing.T) { table Indexable expectErr bool expectedErr string - indexKey interface{} + indexKey any }{ { name: "nil indexKey", @@ -90,13 +90,13 @@ func TestIndexPrefixScan(t *testing.T) { tb, err := NewAutoUInt64Table(AutoUInt64TablePrefix, AutoUInt64TableSeqPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) - idx, err := NewIndex(tb, AutoUInt64TableModelByMetadataPrefix, func(val interface{}) ([]interface{}, error) { - i := []interface{}{val.(*testdata.TableModel).Metadata} + idx, err := NewIndex(tb, AutoUInt64TableModelByMetadataPrefix, func(val any) ([]any, error) { + i := []any{val.(*testdata.TableModel).Metadata} return i, nil }, testdata.TableModel{}.Metadata) require.NoError(t, err) - strIdx, err := NewIndex(tb, 0x1, func(val interface{}) ([]interface{}, error) { - i := []interface{}{val.(*testdata.TableModel).Name} + strIdx, err := NewIndex(tb, 0x1, func(val any) ([]any, error) { + i := []any{val.(*testdata.TableModel).Name} return i, nil }, testdata.TableModel{}.Name) require.NoError(t, err) @@ -125,11 +125,11 @@ func TestIndexPrefixScan(t *testing.T) { } specs := map[string]struct { - start, end interface{} + start, end any expResult []testdata.TableModel expRowIDs []RowID expError *errorsmod.Error - method func(store storetypes.KVStore, start, end interface{}) (Iterator, error) + method func(store storetypes.KVStore, start, end any) (Iterator, error) }{ "exact match with a single result": { start: []byte("metadata-a"), @@ -295,7 +295,7 @@ func TestUniqueIndex(t *testing.T) { myTable, err := NewPrimaryKeyTable(PrimaryKeyTablePrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) - uniqueIdx, err := NewUniqueIndex(myTable, 0x10, func(val interface{}) (interface{}, error) { + uniqueIdx, err := NewUniqueIndex(myTable, 0x10, func(val any) (any, error) { return []byte{val.(*testdata.TableModel).Metadata[0]}, nil }, []byte{}) require.NoError(t, err) diff --git a/x/group/internal/orm/indexer.go b/x/group/internal/orm/indexer.go index 53f266b414..dc5bad7b53 100644 --- a/x/group/internal/orm/indexer.go +++ b/x/group/internal/orm/indexer.go @@ -8,15 +8,15 @@ import ( ) // IndexerFunc creates one or multiple index keys for the source object. -type IndexerFunc func(value interface{}) ([]interface{}, error) +type IndexerFunc func(value any) ([]any, error) // IndexerFunc creates exactly one index key for the source object. -type UniqueIndexerFunc func(value interface{}) (interface{}, error) +type UniqueIndexerFunc func(value any) (any, error) // Indexer manages the persistence of an Index based on searchable keys and operations. type Indexer struct { indexerFunc IndexerFunc - addFunc func(store storetypes.KVStore, secondaryIndexKey interface{}, rowID RowID) error + addFunc func(store storetypes.KVStore, secondaryIndexKey any, rowID RowID) error } // NewIndexer returns an indexer that supports multiple reference keys for an entity. @@ -36,9 +36,9 @@ func NewUniqueIndexer(f UniqueIndexerFunc) (*Indexer, error) { return nil, errors.ErrORMInvalidArgument.Wrap("Indexer func must not be nil") } adaptor := func(indexerFunc UniqueIndexerFunc) IndexerFunc { - return func(v interface{}) ([]interface{}, error) { + return func(v any) ([]any, error) { k, err := indexerFunc(v) - return []interface{}{k}, err + return []any{k}, err } } idx, err := NewIndexer(adaptor(f)) @@ -56,7 +56,7 @@ func (i Indexer) IndexerFunc() IndexerFunc { } // OnCreate persists the secondary index entries for the new object. -func (i Indexer) OnCreate(store storetypes.KVStore, rowID RowID, value interface{}) error { +func (i Indexer) OnCreate(store storetypes.KVStore, rowID RowID, value any) error { secondaryIndexKeys, err := i.indexerFunc(value) if err != nil { return err @@ -71,14 +71,14 @@ func (i Indexer) OnCreate(store storetypes.KVStore, rowID RowID, value interface } // OnDelete removes the secondary index entries for the deleted object. -func (i Indexer) OnDelete(store storetypes.KVStore, rowID RowID, value interface{}) error { +func (i Indexer) OnDelete(store storetypes.KVStore, rowID RowID, value any) error { secondaryIndexKeys, err := i.indexerFunc(value) if err != nil { return err } for _, secondaryIndexKey := range secondaryIndexKeys { - indexKey, err := buildKeyFromParts([]interface{}{secondaryIndexKey, []byte(rowID)}) + indexKey, err := buildKeyFromParts([]any{secondaryIndexKey, []byte(rowID)}) if err != nil { return err } @@ -88,7 +88,7 @@ func (i Indexer) OnDelete(store storetypes.KVStore, rowID RowID, value interface } // OnUpdate rebuilds the secondary index entries for the updated object. -func (i Indexer) OnUpdate(store storetypes.KVStore, rowID RowID, newValue, oldValue interface{}) error { +func (i Indexer) OnUpdate(store storetypes.KVStore, rowID RowID, newValue, oldValue any) error { oldSecIdxKeys, err := i.indexerFunc(oldValue) if err != nil { return err @@ -102,7 +102,7 @@ func (i Indexer) OnUpdate(store storetypes.KVStore, rowID RowID, newValue, oldVa return err } for _, oldIdxKey := range oldKeys { - indexKey, err := buildKeyFromParts([]interface{}{oldIdxKey, []byte(rowID)}) + indexKey, err := buildKeyFromParts([]any{oldIdxKey, []byte(rowID)}) if err != nil { return err } @@ -121,7 +121,7 @@ func (i Indexer) OnUpdate(store storetypes.KVStore, rowID RowID, newValue, oldVa } // uniqueKeysAddFunc enforces keys to be unique -func uniqueKeysAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, rowID RowID) error { +func uniqueKeysAddFunc(store storetypes.KVStore, secondaryIndexKey any, rowID RowID) error { secondaryIndexKeyBytes, err := keyPartBytes(secondaryIndexKey, false) if err != nil { return err @@ -134,7 +134,7 @@ func uniqueKeysAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, return err } - indexKey, err := buildKeyFromParts([]interface{}{secondaryIndexKey, []byte(rowID)}) + indexKey, err := buildKeyFromParts([]any{secondaryIndexKey, []byte(rowID)}) if err != nil { return err } @@ -154,7 +154,7 @@ func checkUniqueIndexKey(store storetypes.KVStore, secondaryIndexKeyBytes []byte } // multiKeyAddFunc allows multiple entries for a key -func multiKeyAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, rowID RowID) error { +func multiKeyAddFunc(store storetypes.KVStore, secondaryIndexKey any, rowID RowID) error { secondaryIndexKeyBytes, err := keyPartBytes(secondaryIndexKey, false) if err != nil { return err @@ -163,7 +163,7 @@ func multiKeyAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, ro return errorsmod.Wrap(errors.ErrORMInvalidArgument, "empty index key") } - encodedKey, err := buildKeyFromParts([]interface{}{secondaryIndexKey, []byte(rowID)}) + encodedKey, err := buildKeyFromParts([]any{secondaryIndexKey, []byte(rowID)}) if err != nil { return err } @@ -176,8 +176,8 @@ func multiKeyAddFunc(store storetypes.KVStore, secondaryIndexKey interface{}, ro } // difference returns the list of elements that are in a but not in b. -func difference(a, b []interface{}) ([]interface{}, error) { - set := make(map[interface{}]struct{}, len(b)) +func difference(a, b []any) ([]any, error) { + set := make(map[any]struct{}, len(b)) for _, v := range b { bt, err := keyPartBytes(v, true) if err != nil { @@ -185,7 +185,7 @@ func difference(a, b []interface{}) ([]interface{}, error) { } set[string(bt)] = struct{}{} } - var result []interface{} + var result []any for _, v := range a { bt, err := keyPartBytes(v, true) if err != nil { @@ -200,12 +200,12 @@ func difference(a, b []interface{}) ([]interface{}, error) { // pruneEmptyKeys drops any empty key from IndexerFunc f returned func pruneEmptyKeys(f IndexerFunc) IndexerFunc { - return func(v interface{}) ([]interface{}, error) { + return func(v any) ([]any, error) { keys, err := f(v) if err != nil || keys == nil { return keys, err } - r := make([]interface{}, 0, len(keys)) + r := make([]any, 0, len(keys)) for i := range keys { key, err := keyPartBytes(keys[i], true) if err != nil { diff --git a/x/group/internal/orm/indexer_test.go b/x/group/internal/orm/indexer_test.go index 0787bfc4ab..7465892bd1 100644 --- a/x/group/internal/orm/indexer_test.go +++ b/x/group/internal/orm/indexer_test.go @@ -30,7 +30,7 @@ func TestNewIndexer(t *testing.T) { }, { name: "all not nil", - indexerFunc: func(interface{}) ([]interface{}, error) { return nil, nil }, + indexerFunc: func(any) ([]any, error) { return nil, nil }, expectErr: false, }, } @@ -63,7 +63,7 @@ func TestNewUniqueIndexer(t *testing.T) { }, { name: "all not nil", - indexerFunc: func(interface{}) (interface{}, error) { return nil, nil }, + indexerFunc: func(any) (any, error) { return nil, nil }, expectErr: false, }, } @@ -86,54 +86,54 @@ func TestIndexerOnCreate(t *testing.T) { specs := map[string]struct { srcFunc IndexerFunc - expIndexKeys []interface{} + expIndexKeys []any expRowIDs []RowID expAddFuncCalled bool expErr error }{ "single key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1)}, nil }, expAddFuncCalled: true, - expIndexKeys: []interface{}{uint64(1)}, + expIndexKeys: []any{uint64(1)}, expRowIDs: []RowID{myRowID}, }, "multi key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1), uint64(128)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1), uint64(128)}, nil }, expAddFuncCalled: true, - expIndexKeys: []interface{}{uint64(1), uint64(128)}, + expIndexKeys: []any{uint64(1), uint64(128)}, expRowIDs: []RowID{myRowID, myRowID}, }, "empty key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{[]byte{}}, nil + srcFunc: func(value any) ([]any, error) { + return []any{[]byte{}}, nil }, expAddFuncCalled: false, }, "nil key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{nil}, nil + srcFunc: func(value any) ([]any, error) { + return []any{nil}, nil }, expErr: fmt.Errorf("type %T not allowed as key part", nil), expAddFuncCalled: false, }, "empty key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{}, nil + srcFunc: func(value any) ([]any, error) { + return []any{}, nil }, expAddFuncCalled: false, }, "nil key": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, nil }, expAddFuncCalled: false, }, "error case": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, stdErrors.New("test") }, expErr: stdErrors.New("test"), @@ -174,14 +174,14 @@ func TestIndexerOnDelete(t *testing.T) { expErr error }{ "single key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1)}, nil }, expDeletedKeys: []RowID{append(EncodeSequence(1), myRowID...)}, }, "multi key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1), uint64(128)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1), uint64(128)}, nil }, expDeletedKeys: []RowID{ append(EncodeSequence(1), myRowID...), @@ -189,28 +189,28 @@ func TestIndexerOnDelete(t *testing.T) { }, }, "empty key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{}, nil + srcFunc: func(value any) ([]any, error) { + return []any{}, nil }, }, "nil key": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, nil }, }, "empty key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{[]byte{}}, nil + srcFunc: func(value any) ([]any, error) { + return []any{[]byte{}}, nil }, }, "nil key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{nil}, nil + srcFunc: func(value any) ([]any, error) { + return []any{nil}, nil }, expErr: fmt.Errorf("type %T not allowed as key part", nil), }, "error case": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, stdErrors.New("test") }, expErr: stdErrors.New("test"), @@ -255,17 +255,17 @@ func TestIndexerOnUpdate(t *testing.T) { expAddedKeys []RowID expDeletedKeys []RowID expErr error - addFunc func(storetypes.KVStore, interface{}, RowID) error + addFunc func(storetypes.KVStore, any, RowID) error }{ "single key - same key, no update": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1)}, nil }, }, "single key - different key, replaced": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { keys := []uint64{1, 2} - return []interface{}{keys[value.(int)]}, nil + return []any{keys[value.(int)]}, nil }, expAddedKeys: []RowID{ append(EncodeSequence(2), myRowID...), @@ -275,14 +275,14 @@ func TestIndexerOnUpdate(t *testing.T) { }, }, "multi key - same key, no update": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{uint64(1), uint64(2)}, nil + srcFunc: func(value any) ([]any, error) { + return []any{uint64(1), uint64(2)}, nil }, }, "multi key - replaced": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { keys := []uint64{1, 2, 3, 4} - return []interface{}{keys[value.(int)], keys[value.(int)+2]}, nil + return []any{keys[value.(int)], keys[value.(int)+2]}, nil }, expAddedKeys: []RowID{ append(EncodeSequence(2), myRowID...), @@ -294,48 +294,48 @@ func TestIndexerOnUpdate(t *testing.T) { }, }, "empty key": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{}, nil + srcFunc: func(value any) ([]any, error) { + return []any{}, nil }, }, "nil key": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, nil }, }, "empty key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{[]byte{}}, nil + srcFunc: func(value any) ([]any, error) { + return []any{[]byte{}}, nil }, }, "nil key in slice": { - srcFunc: func(value interface{}) ([]interface{}, error) { - return []interface{}{nil}, nil + srcFunc: func(value any) ([]any, error) { + return []any{nil}, nil }, expErr: fmt.Errorf("type %T not allowed as key part", nil), }, "error case with new value": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { return nil, stdErrors.New("test") }, expErr: stdErrors.New("test"), }, "error case with old value": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { var err error if value.(int)%2 == 1 { err = stdErrors.New("test") } - return []interface{}{uint64(1)}, err + return []any{uint64(1)}, err }, expErr: stdErrors.New("test"), }, "error case on persisting new keys": { - srcFunc: func(value interface{}) ([]interface{}, error) { + srcFunc: func(value any) ([]any, error) { keys := []uint64{1, 2} - return []interface{}{keys[value.(int)]}, nil + return []any{keys[value.(int)]}, nil }, - addFunc: func(_ storetypes.KVStore, _ interface{}, _ RowID) error { + addFunc: func(_ storetypes.KVStore, _ any, _ RowID) error { return stdErrors.New("test") }, expErr: stdErrors.New("test"), @@ -458,29 +458,29 @@ func TestMultiKeyAddFunc(t *testing.T) { func TestDifference(t *testing.T) { specs := map[string]struct { - srcA []interface{} - srcB []interface{} - expResult []interface{} + srcA []any + srcB []any + expResult []any expErr bool }{ "all of A": { - srcA: []interface{}{"a", "b"}, - srcB: []interface{}{"c"}, - expResult: []interface{}{"a", "b"}, + srcA: []any{"a", "b"}, + srcB: []any{"c"}, + expResult: []any{"a", "b"}, }, "A - B": { - srcA: []interface{}{"a", "b"}, - srcB: []interface{}{"b", "c", "d"}, - expResult: []interface{}{"a"}, + srcA: []any{"a", "b"}, + srcB: []any{"b", "c", "d"}, + expResult: []any{"a"}, }, "type in A not allowed": { - srcA: []interface{}{1}, - srcB: []interface{}{"b", "c", "d"}, + srcA: []any{1}, + srcB: []any{"b", "c", "d"}, expErr: true, }, "type in B not allowed": { - srcA: []interface{}{"b", "c", "d"}, - srcB: []interface{}{1}, + srcA: []any{"b", "c", "d"}, + srcB: []any{1}, expErr: true, }, } @@ -500,46 +500,46 @@ func TestDifference(t *testing.T) { func TestPruneEmptyKeys(t *testing.T) { specs := map[string]struct { srcFunc IndexerFunc - expResult []interface{} + expResult []any expError error }{ "non empty": { - srcFunc: func(v interface{}) ([]interface{}, error) { - return []interface{}{uint64(0), uint64(1)}, nil + srcFunc: func(v any) ([]any, error) { + return []any{uint64(0), uint64(1)}, nil }, - expResult: []interface{}{uint64(0), uint64(1)}, + expResult: []any{uint64(0), uint64(1)}, }, "empty": { - srcFunc: func(v interface{}) ([]interface{}, error) { - return []interface{}{}, nil + srcFunc: func(v any) ([]any, error) { + return []any{}, nil }, - expResult: []interface{}{}, + expResult: []any{}, }, "nil": { - srcFunc: func(v interface{}) ([]interface{}, error) { + srcFunc: func(v any) ([]any, error) { return nil, nil }, }, "empty in the beginning": { - srcFunc: func(v interface{}) ([]interface{}, error) { - return []interface{}{[]byte{}, uint64(0), uint64(1)}, nil + srcFunc: func(v any) ([]any, error) { + return []any{[]byte{}, uint64(0), uint64(1)}, nil }, - expResult: []interface{}{uint64(0), uint64(1)}, + expResult: []any{uint64(0), uint64(1)}, }, "empty in the middle": { - srcFunc: func(v interface{}) ([]interface{}, error) { - return []interface{}{uint64(0), []byte{}, uint64(1)}, nil + srcFunc: func(v any) ([]any, error) { + return []any{uint64(0), []byte{}, uint64(1)}, nil }, - expResult: []interface{}{uint64(0), uint64(1)}, + expResult: []any{uint64(0), uint64(1)}, }, "empty at the end": { - srcFunc: func(v interface{}) ([]interface{}, error) { - return []interface{}{uint64(0), uint64(1), []byte{}}, nil + srcFunc: func(v any) ([]any, error) { + return []any{uint64(0), uint64(1), []byte{}}, nil }, - expResult: []interface{}{uint64(0), uint64(1)}, + expResult: []any{uint64(0), uint64(1)}, }, "error passed": { - srcFunc: func(v interface{}) ([]interface{}, error) { + srcFunc: func(v any) ([]any, error) { return nil, stdErrors.New("test") }, expError: stdErrors.New("test"), @@ -558,12 +558,12 @@ func TestPruneEmptyKeys(t *testing.T) { } type addFuncRecorder struct { - secondaryIndexKeys []interface{} + secondaryIndexKeys []any rowIDs []RowID called bool } -func (c *addFuncRecorder) add(_ storetypes.KVStore, key interface{}, rowID RowID) error { +func (c *addFuncRecorder) add(_ storetypes.KVStore, key any, rowID RowID) error { c.secondaryIndexKeys = append(c.secondaryIndexKeys, key) c.rowIDs = append(c.rowIDs, rowID) c.called = true diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index 0d78667d41..f9b70198a1 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -225,7 +225,7 @@ func Paginate( // *[]Model Because of Go's type system, using []Model type would not work for us. // Instead we use a placeholder type and the validation is done during the // runtime. -type ModelSlicePtr interface{} +type ModelSlicePtr any // ReadAll consumes all values for the iterator and stores them in a new slice at the passed ModelSlicePtr. // The slice can be empty when the iterator does not return any values but not nil. The iterator diff --git a/x/group/internal/orm/iterator_test.go b/x/group/internal/orm/iterator_test.go index 0ef2d9333f..2962417b9e 100644 --- a/x/group/internal/orm/iterator_test.go +++ b/x/group/internal/orm/iterator_test.go @@ -204,8 +204,8 @@ func TestPaginate(t *testing.T) { tb, err := NewAutoUInt64Table(AutoUInt64TablePrefix, AutoUInt64TableSeqPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) - idx, err := NewIndex(tb, AutoUInt64TableModelByMetadataPrefix, func(val interface{}) ([]interface{}, error) { - return []interface{}{val.(*testdata.TableModel).Metadata}, nil + idx, err := NewIndex(tb, AutoUInt64TableModelByMetadataPrefix, func(val any) ([]any, error) { + return []any{val.(*testdata.TableModel).Metadata}, nil }, testdata.TableModel{}.Metadata) require.NoError(t, err) diff --git a/x/group/internal/orm/key_codec.go b/x/group/internal/orm/key_codec.go index 53c1dadc45..e79bac27af 100644 --- a/x/group/internal/orm/key_codec.go +++ b/x/group/internal/orm/key_codec.go @@ -18,7 +18,7 @@ const MaxBytesLen = 255 // - []byte is encoded with a single byte length prefix // - strings are null-terminated // - integers are encoded using 8 byte big endian. -func buildKeyFromParts(parts []interface{}) ([]byte, error) { +func buildKeyFromParts(parts []any) ([]byte, error) { bytesSlice := make([][]byte, len(parts)) totalLen := 0 var err error @@ -36,7 +36,7 @@ func buildKeyFromParts(parts []interface{}) ([]byte, error) { return key, nil } -func keyPartBytes(part interface{}, last bool) ([]byte, error) { +func keyPartBytes(part any, last bool) ([]byte, error) { switch v := part.(type) { case []byte: if last || len(v) == 0 { @@ -79,7 +79,7 @@ func NullTerminatedBytes(s string) []byte { // stripRowID returns the RowID from the indexKey based on secondaryIndexKey type. // It is the reverse operation to buildKeyFromParts for index keys // where the first part is the encoded secondaryIndexKey and the second part is the RowID. -func stripRowID(indexKey []byte, secondaryIndexKey interface{}) (RowID, error) { +func stripRowID(indexKey []byte, secondaryIndexKey any) (RowID, error) { switch v := secondaryIndexKey.(type) { case []byte: searchableKeyLen := indexKey[0] diff --git a/x/group/internal/orm/orm_scenario_test.go b/x/group/internal/orm/orm_scenario_test.go index 7b2391e2d8..19ab717dc8 100644 --- a/x/group/internal/orm/orm_scenario_test.go +++ b/x/group/internal/orm/orm_scenario_test.go @@ -395,7 +395,7 @@ func TestExportImportStatePrimaryKeyTable(t *testing.T) { } } -func assertIndex(t *testing.T, store storetypes.KVStore, index Index, v testdata.TableModel, searchKey interface{}) { +func assertIndex(t *testing.T, store storetypes.KVStore, index Index, v testdata.TableModel, searchKey any) { t.Helper() it, err := index.Get(store, searchKey) diff --git a/x/group/internal/orm/primary_key.go b/x/group/internal/orm/primary_key.go index e8f30d6beb..1a37a035e5 100644 --- a/x/group/internal/orm/primary_key.go +++ b/x/group/internal/orm/primary_key.go @@ -42,7 +42,7 @@ type PrimaryKeyed interface { // // IMPORTANT: []byte parts are encoded with a single byte length prefix, // so cannot be longer than 255 bytes. - PrimaryKeyFields() []interface{} + PrimaryKeyFields() []any proto.Message } @@ -159,6 +159,6 @@ func (a PrimaryKeyTable) Export(store storetypes.KVStore, dest ModelSlicePtr) (u // Import clears the table and initializes it from the given data interface{}. // data should be a slice of structs that implement PrimaryKeyed. -func (a PrimaryKeyTable) Import(store storetypes.KVStore, data interface{}, seqValue uint64) error { +func (a PrimaryKeyTable) Import(store storetypes.KVStore, data any, seqValue uint64) error { return a.table.Import(store, data, seqValue) } diff --git a/x/group/internal/orm/table.go b/x/group/internal/orm/table.go index f15d9f7639..a97ab03bfe 100644 --- a/x/group/internal/orm/table.go +++ b/x/group/internal/orm/table.go @@ -252,7 +252,7 @@ func (a table) Export(store types.KVStore, dest ModelSlicePtr) (uint64, error) { // Import clears the table and initializes it from the given data interface{}. // data should be a slice of structs that implement PrimaryKeyed. -func (a table) Import(store types.KVStore, data interface{}, _ uint64) error { +func (a table) Import(store types.KVStore, data any, _ uint64) error { // Clear all data keys := a.keys(store) for _, key := range keys { @@ -268,7 +268,7 @@ func (a table) Import(store types.KVStore, data interface{}, _ uint64) error { } // Import values from slice - for i := 0; i < modelSlice.Len(); i++ { + for i := range modelSlice.Len() { obj, ok := modelSlice.Index(i).Interface().(PrimaryKeyed) if !ok { return errorsmod.Wrapf(errors.ErrORMInvalidArgument, "unsupported type :%s", reflect.TypeOf(data).Elem().Elem()) diff --git a/x/group/internal/orm/types.go b/x/group/internal/orm/types.go index da6f2c6a1b..ab4f26861a 100644 --- a/x/group/internal/orm/types.go +++ b/x/group/internal/orm/types.go @@ -38,15 +38,15 @@ type Validateable interface { // variable length and scanned iteratively. type Index interface { // Has checks if a key exists. Panics on nil key. - Has(store storetypes.KVStore, key interface{}) (bool, error) + Has(store storetypes.KVStore, key any) (bool, error) // Get returns a result iterator for the searchKey. // searchKey must not be nil. - Get(store storetypes.KVStore, searchKey interface{}) (Iterator, error) + Get(store storetypes.KVStore, searchKey any) (Iterator, error) // GetPaginated returns a result iterator for the searchKey and optional pageRequest. // searchKey must not be nil. - GetPaginated(store storetypes.KVStore, searchKey interface{}, pageRequest *query.PageRequest) (Iterator, error) + GetPaginated(store storetypes.KVStore, searchKey any, pageRequest *query.PageRequest) (Iterator, error) // PrefixScan returns an Iterator over a domain of keys in ascending order. End is exclusive. // Start is an MultiKeyIndex key or prefix. It must be less than end, or the Iterator is invalid and error is returned. @@ -64,7 +64,7 @@ type Index interface { // it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. - PrefixScan(store storetypes.KVStore, startI, endI interface{}) (Iterator, error) + PrefixScan(store storetypes.KVStore, startI, endI any) (Iterator, error) // ReversePrefixScan returns an Iterator over a domain of keys in descending order. End is exclusive. // Start is an MultiKeyIndex key or prefix. It must be less than end, or the Iterator is invalid and error is returned. @@ -75,7 +75,7 @@ type Index interface { // this as an endpoint to the public without further limits. See `LimitIterator` // // CONTRACT: No writes may happen within a domain while an iterator exists over it. - ReversePrefixScan(store storetypes.KVStore, startI, endI interface{}) (Iterator, error) + ReversePrefixScan(store storetypes.KVStore, startI, endI any) (Iterator, error) } // Iterator allows iteration through a sequence of key value pairs diff --git a/x/group/internal/orm/types_test.go b/x/group/internal/orm/types_test.go index afcc59853d..736bf6ffd5 100644 --- a/x/group/internal/orm/types_test.go +++ b/x/group/internal/orm/types_test.go @@ -34,7 +34,7 @@ func TestTypeSafeRowGetter(t *testing.T) { specs := map[string]struct { srcRowID RowID srcModelType reflect.Type - expObj interface{} + expObj any expErr *errorsmod.Error }{ "happy path": { diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index b6076622ad..a4621ed087 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -96,12 +96,12 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes if err != nil { panic(err.Error()) } - k.groupByAdminIndex, err = orm.NewIndex(groupTable, GroupByAdminIndexPrefix, func(val interface{}) ([]interface{}, error) { + k.groupByAdminIndex, err = orm.NewIndex(groupTable, GroupByAdminIndexPrefix, func(val any) ([]any, error) { addr, err := accKeeper.AddressCodec().StringToBytes(val.(*group.GroupInfo).Admin) if err != nil { return nil, err } - return []interface{}{addr}, nil + return []any{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -113,20 +113,20 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes if err != nil { panic(err.Error()) } - k.groupMemberByGroupIndex, err = orm.NewIndex(groupMemberTable, GroupMemberByGroupIndexPrefix, func(val interface{}) ([]interface{}, error) { + k.groupMemberByGroupIndex, err = orm.NewIndex(groupMemberTable, GroupMemberByGroupIndexPrefix, func(val any) ([]any, error) { group := val.(*group.GroupMember).GroupId - return []interface{}{group}, nil + return []any{group}, nil }, group.GroupMember{}.GroupId) if err != nil { panic(err.Error()) } - k.groupMemberByMemberIndex, err = orm.NewIndex(groupMemberTable, GroupMemberByMemberIndexPrefix, func(val interface{}) ([]interface{}, error) { + k.groupMemberByMemberIndex, err = orm.NewIndex(groupMemberTable, GroupMemberByMemberIndexPrefix, func(val any) ([]any, error) { memberAddr := val.(*group.GroupMember).Member.Address addr, err := accKeeper.AddressCodec().StringToBytes(memberAddr) if err != nil { return nil, err } - return []interface{}{addr}, nil + return []any{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -139,19 +139,19 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes if err != nil { panic(err.Error()) } - k.groupPolicyByGroupIndex, err = orm.NewIndex(groupPolicyTable, GroupPolicyByGroupIndexPrefix, func(value interface{}) ([]interface{}, error) { - return []interface{}{value.(*group.GroupPolicyInfo).GroupId}, nil + k.groupPolicyByGroupIndex, err = orm.NewIndex(groupPolicyTable, GroupPolicyByGroupIndexPrefix, func(value any) ([]any, error) { + return []any{value.(*group.GroupPolicyInfo).GroupId}, nil }, group.GroupPolicyInfo{}.GroupId) if err != nil { panic(err.Error()) } - k.groupPolicyByAdminIndex, err = orm.NewIndex(groupPolicyTable, GroupPolicyByAdminIndexPrefix, func(value interface{}) ([]interface{}, error) { + k.groupPolicyByAdminIndex, err = orm.NewIndex(groupPolicyTable, GroupPolicyByAdminIndexPrefix, func(value any) ([]any, error) { admin := value.(*group.GroupPolicyInfo).Admin addr, err := accKeeper.AddressCodec().StringToBytes(admin) if err != nil { return nil, err } - return []interface{}{addr}, nil + return []any{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -163,20 +163,20 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes if err != nil { panic(err.Error()) } - k.proposalByGroupPolicyIndex, err = orm.NewIndex(proposalTable, ProposalByGroupPolicyIndexPrefix, func(value interface{}) ([]interface{}, error) { + k.proposalByGroupPolicyIndex, err = orm.NewIndex(proposalTable, ProposalByGroupPolicyIndexPrefix, func(value any) ([]any, error) { account := value.(*group.Proposal).GroupPolicyAddress addr, err := accKeeper.AddressCodec().StringToBytes(account) if err != nil { return nil, err } - return []interface{}{addr}, nil + return []any{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) } - k.proposalsByVotingPeriodEnd, err = orm.NewIndex(proposalTable, ProposalsByVotingPeriodEndPrefix, func(value interface{}) ([]interface{}, error) { + k.proposalsByVotingPeriodEnd, err = orm.NewIndex(proposalTable, ProposalsByVotingPeriodEndPrefix, func(value any) ([]any, error) { votingPeriodEnd := value.(*group.Proposal).VotingPeriodEnd - return []interface{}{sdk.FormatTimeBytes(votingPeriodEnd)}, nil + return []any{sdk.FormatTimeBytes(votingPeriodEnd)}, nil }, []byte{}) if err != nil { panic(err.Error()) @@ -188,18 +188,18 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router baseapp.Mes if err != nil { panic(err.Error()) } - k.voteByProposalIndex, err = orm.NewIndex(voteTable, VoteByProposalIndexPrefix, func(value interface{}) ([]interface{}, error) { - return []interface{}{value.(*group.Vote).ProposalId}, nil + k.voteByProposalIndex, err = orm.NewIndex(voteTable, VoteByProposalIndexPrefix, func(value any) ([]any, error) { + return []any{value.(*group.Vote).ProposalId}, nil }, group.Vote{}.ProposalId) if err != nil { panic(err.Error()) } - k.voteByVoterIndex, err = orm.NewIndex(voteTable, VoteByVoterIndexPrefix, func(value interface{}) ([]interface{}, error) { + k.voteByVoterIndex, err = orm.NewIndex(voteTable, VoteByVoterIndexPrefix, func(value any) ([]any, error) { addr, err := accKeeper.AddressCodec().StringToBytes(value.(*group.Vote).Voter) if err != nil { return nil, err } - return []interface{}{addr}, nil + return []any{addr}, nil }, []byte{}) if err != nil { panic(err.Error()) diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go index 5fb4a7bf53..8717bef0f5 100644 --- a/x/group/keeper/msg_server_test.go +++ b/x/group/keeper/msg_server_test.go @@ -35,7 +35,7 @@ func (s *TestSuite) TestCreateGroupWithLotsOfMembers() { func (s *TestSuite) createGroupAndGetMembers(numMembers int) []*group.GroupMember { addressPool := simtestutil.CreateIncrementalAccounts(numMembers) members := make([]group.MemberRequest, numMembers) - for i := 0; i < len(members); i++ { + for i := range members { members[i] = group.MemberRequest{ Address: addressPool[i].String(), Weight: "1", @@ -1823,7 +1823,7 @@ func (s *TestSuite) TestSubmitProposal() { }, "with try exec": { preRun: func(msgs []sdk.Msg) { - for i := 0; i < len(msgs); i++ { + for i := range msgs { s.bankKeeper.EXPECT().Send(gomock.Any(), msgs[i]).Return(nil, nil) } }, diff --git a/x/group/simulation/genesis.go b/x/group/simulation/genesis.go index d5273b97bb..f390bb447f 100644 --- a/x/group/simulation/genesis.go +++ b/x/group/simulation/genesis.go @@ -22,7 +22,7 @@ const ( func checkAccExists(acc sdk.AccAddress, g []*group.GroupMember, lastIndex int) bool { s := acc.String() - for i := 0; i < lastIndex; i++ { + for i := range lastIndex { if g[i].Member.Address == s { return true } @@ -32,7 +32,7 @@ func checkAccExists(acc sdk.AccAddress, g []*group.GroupMember, lastIndex int) b func getGroups(r *rand.Rand, accounts []simtypes.Account) []*group.GroupInfo { groups := make([]*group.GroupInfo, 3) - for i := 0; i < 3; i++ { + for i := range 3 { acc, _ := simtypes.RandomAcc(r, accounts) groups[i] = &group.GroupInfo{ Id: uint64(i + 1), @@ -47,7 +47,7 @@ func getGroups(r *rand.Rand, accounts []simtypes.Account) []*group.GroupInfo { func getGroupMembers(r *rand.Rand, accounts []simtypes.Account) []*group.GroupMember { groupMembers := make([]*group.GroupMember, 3) - for i := 0; i < 3; i++ { + for i := range 3 { acc, _ := simtypes.RandomAcc(r, accounts) for checkAccExists(acc.Address, groupMembers, i) { acc, _ = simtypes.RandomAcc(r, accounts) @@ -100,7 +100,7 @@ func getGroupPolicies(r *rand.Rand, simState *module.SimulationState) []*group.G func getProposals(r *rand.Rand, simState *module.SimulationState, groupPolicies []*group.GroupPolicyInfo) []*group.Proposal { proposals := make([]*group.Proposal, 3) proposers := []string{simState.Accounts[0].Address.String(), simState.Accounts[1].Address.String()} - for i := 0; i < 3; i++ { + for i := range 3 { idx := r.Intn(len(groupPolicies)) groupPolicyAddress := groupPolicies[idx].Address to, _ := simtypes.RandomAcc(r, simState.Accounts) @@ -144,7 +144,7 @@ func getProposals(r *rand.Rand, simState *module.SimulationState, groupPolicies func getVotes(r *rand.Rand, simState *module.SimulationState) []*group.Vote { votes := make([]*group.Vote, 3) - for i := 0; i < 3; i++ { + for i := range 3 { votes[i] = &group.Vote{ ProposalId: uint64(i + 1), Voter: simState.Accounts[i].Address.String(), diff --git a/x/group/simulation/msg_factory.go b/x/group/simulation/msg_factory.go index 90c92d2cc9..95666946c4 100644 --- a/x/group/simulation/msg_factory.go +++ b/x/group/simulation/msg_factory.go @@ -250,7 +250,7 @@ func MsgExecFactory(k keeper.Keeper, s *SharedState) simsx.SimMsgFactoryFn[*grou } func randomGroupPolicyWithAdmin(ctx context.Context, testData *simsx.ChainDataSource, reporter simsx.SimulationReporter, k keeper.Keeper, s *SharedState) (*group.GroupPolicyInfo, simsx.SimAccount) { - for i := 0; i < 5; i++ { + for range 5 { _, groupPolicy := randomGroupPolicyX(ctx, testData, reporter, k, s) if groupPolicy != nil && testData.HasAccount(groupPolicy.Admin) { return groupPolicy, testData.GetAccount(reporter, groupPolicy.Admin) @@ -450,7 +450,7 @@ func randomGroupPolicyX( k keeper.Keeper, s *SharedState, ) (*group.GroupInfo, *group.GroupPolicyInfo) { - for i := 0; i < 5; i++ { + for range 5 { groupInfo := randomGroupX(ctx, k, testdata, reporter, s) if reporter.IsSkipped() { return nil, nil diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index b0a42d454d..d91c7febd2 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -153,7 +153,7 @@ func WeightedOperations( // create two proposals for weightedOperations var createProposalOps simulation.WeightedOperations - for i := 0; i < 2; i++ { + for range 2 { createProposalOps = append(createProposalOps, simulation.NewWeightedOperation( weightMsgSubmitProposal, simulateMsgSubmitProposal(pCdc, txGen, ak, bk, k, state), @@ -1491,7 +1491,7 @@ func genGroupMembers(r *rand.Rand, accounts []simtypes.Account) []group.MemberRe membersLen := simtypes.RandIntBetween(r, 1, maxMembers) members := make([]group.MemberRequest, membersLen) - for i := 0; i < membersLen; i++ { + for i := range membersLen { members[i] = group.MemberRequest{ Address: accounts[i].Address.String(), Weight: fmt.Sprintf("%d", simtypes.RandIntBetween(r, 1, 10)), diff --git a/x/group/types.go b/x/group/types.go index 4c498b1b1b..cab7cfc021 100644 --- a/x/group/types.go +++ b/x/group/types.go @@ -292,8 +292,8 @@ func (g GroupPolicyInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error return unpacker.UnpackAny(g.DecisionPolicy, &decisionPolicy) } -func (g GroupInfo) PrimaryKeyFields() []interface{} { - return []interface{}{g.Id} +func (g GroupInfo) PrimaryKeyFields() []any { + return []any{g.Id} } // ValidateBasic does basic validation on group info. @@ -316,14 +316,14 @@ func (g GroupInfo) ValidateBasic() error { return nil } -func (g GroupPolicyInfo) PrimaryKeyFields() []interface{} { +func (g GroupPolicyInfo) PrimaryKeyFields() []any { addr := sdk.MustAccAddressFromBech32(g.Address) - return []interface{}{addr.Bytes()} + return []any{addr.Bytes()} } -func (g Proposal) PrimaryKeyFields() []interface{} { - return []interface{}{g.Id} +func (g Proposal) PrimaryKeyFields() []any { + return []any{g.Id} } // ValidateBasic does basic validation on group policy info. @@ -354,10 +354,10 @@ func (g GroupPolicyInfo) ValidateBasic() error { return nil } -func (g GroupMember) PrimaryKeyFields() []interface{} { +func (g GroupMember) PrimaryKeyFields() []any { addr := sdk.MustAccAddressFromBech32(g.Member.Address) - return []interface{}{g.GroupId, addr.Bytes()} + return []any{g.GroupId, addr.Bytes()} } // ValidateBasic does basic validation on group member. @@ -423,10 +423,10 @@ func (g Proposal) ValidateBasic() error { return nil } -func (v Vote) PrimaryKeyFields() []interface{} { +func (v Vote) PrimaryKeyFields() []any { addr := sdk.MustAccAddressFromBech32(v.Voter) - return []interface{}{v.ProposalId, addr.Bytes()} + return []any{v.ProposalId, addr.Bytes()} } var _ orm.Validateable = Vote{} diff --git a/x/mint/types/params.go b/x/mint/types/params.go index 4c31610d6f..b25d5aac7d 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -64,7 +64,7 @@ func (p Params) Validate() error { return nil } -func validateMintDenom(i interface{}) error { +func validateMintDenom(i any) error { v, ok := i.(string) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -80,7 +80,7 @@ func validateMintDenom(i interface{}) error { return nil } -func validateInflationRateChange(i interface{}) error { +func validateInflationRateChange(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -99,7 +99,7 @@ func validateInflationRateChange(i interface{}) error { return nil } -func validateInflationMax(i interface{}) error { +func validateInflationMax(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -118,7 +118,7 @@ func validateInflationMax(i interface{}) error { return nil } -func validateInflationMin(i interface{}) error { +func validateInflationMin(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -137,7 +137,7 @@ func validateInflationMin(i interface{}) error { return nil } -func validateGoalBonded(i interface{}) error { +func validateGoalBonded(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -156,7 +156,7 @@ func validateGoalBonded(i interface{}) error { return nil } -func validateBlocksPerYear(i interface{}) error { +func validateBlocksPerYear(i any) error { v, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index 7c916b86a9..3f68c91429 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -49,7 +49,7 @@ func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } -func validateNoOp(_ interface{}) error { return nil } +func validateNoOp(_ any) error { return nil } func TestKeeper(t *testing.T) { kvs := []struct { @@ -143,7 +143,7 @@ func TestKeeper(t *testing.T) { } } -func indirect(ptr interface{}) interface{} { +func indirect(ptr any) any { return reflect.ValueOf(ptr).Elem().Interface() } @@ -175,9 +175,9 @@ func TestSubspace(t *testing.T) { kvs := []struct { key string - param interface{} - zero interface{} - ptr interface{} + param any + zero any + ptr any }{ {"string", "test", "", new(string)}, {"bool", true, false, new(bool)}, diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 9e1a2f19b7..b900b55581 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -35,7 +35,7 @@ func SimulateParamChangeProposalContent(paramChangePool []simulation.LegacyParam // perm here takes at most len(paramChangePool) calls to random paramChoices := r.Perm(len(paramChangePool)) - for i := 0; i < numChanges; i++ { + for i := range numChanges { spc := paramChangePool[paramChoices[i]] // add a new distinct parameter to the set of changes paramChanges[i] = proposal.NewParamChange(spc.Subspace(), spc.Key(), spc.SimValue()(r)) diff --git a/x/params/types/common_test.go b/x/params/types/common_test.go index 46ae0be8ca..2300a4106d 100644 --- a/x/params/types/common_test.go +++ b/x/params/types/common_test.go @@ -33,7 +33,7 @@ type paramsV2 struct { MaxRedelegationEntries uint32 `json:"max_redelegation_entries" yaml:"max_redelegation_entries"` } -func validateUnbondingTime(i interface{}) error { +func validateUnbondingTime(i any) error { v, ok := i.(time.Duration) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -46,7 +46,7 @@ func validateUnbondingTime(i interface{}) error { return nil } -func validateMaxValidators(i interface{}) error { +func validateMaxValidators(i any) error { _, ok := i.(uint16) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -55,7 +55,7 @@ func validateMaxValidators(i interface{}) error { return nil } -func validateBondDenom(i interface{}) error { +func validateBondDenom(i any) error { v, ok := i.(string) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -68,7 +68,7 @@ func validateBondDenom(i interface{}) error { return nil } -func validateMaxRedelegationEntries(i interface{}) error { +func validateMaxRedelegationEntries(i any) error { _, ok := i.(uint32) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/params/types/deref_test.go b/x/params/types/deref_test.go index 1cd4406e57..ecf9b7ce89 100644 --- a/x/params/types/deref_test.go +++ b/x/params/types/deref_test.go @@ -9,7 +9,7 @@ import ( func TestKeyTableUnfurlsPointers(t *testing.T) { tbl := NewKeyTable() - validator := func(_ interface{}) error { + validator := func(_ any) error { return nil } tbl = tbl.RegisterType(ParamSetPair{ diff --git a/x/params/types/paramset.go b/x/params/types/paramset.go index 80d0852be4..1c196b61ad 100644 --- a/x/params/types/paramset.go +++ b/x/params/types/paramset.go @@ -1,19 +1,19 @@ package types type ( - ValueValidatorFn func(value interface{}) error + ValueValidatorFn func(value any) error // ParamSetPair is used for associating paramsubspace key and field of param // structs. ParamSetPair struct { Key []byte - Value interface{} + Value any ValidatorFn ValueValidatorFn } ) // NewParamSetPair creates a new ParamSetPair instance. -func NewParamSetPair(key []byte, value interface{}, vfn ValueValidatorFn) ParamSetPair { +func NewParamSetPair(key []byte, value any, vfn ValueValidatorFn) ParamSetPair { return ParamSetPair{key, value, vfn} } diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index baa95ff2a5..392851678e 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -2,6 +2,7 @@ package types import ( "fmt" + "maps" "reflect" "cosmossdk.io/store/prefix" @@ -57,9 +58,7 @@ func (s Subspace) WithKeyTable(table KeyTable) Subspace { panic("WithKeyTable() called on already initialized Subspace") } - for k, v := range table.m { - s.table.m[k] = v - } + maps.Copy(s.table.m, table.m) // Allocate additional capacity for Subspace.name // So we don't have to allocate extra space each time appending to the key @@ -86,7 +85,7 @@ func (s Subspace) transientStore(ctx sdk.Context) storetypes.KVStore { // Validate attempts to validate a parameter value by its key. If the key is not // registered or if the validation of the value fails, an error is returned. -func (s Subspace) Validate(ctx sdk.Context, key []byte, value interface{}) error { +func (s Subspace) Validate(ctx sdk.Context, key []byte, value any) error { attr, ok := s.table.m[string(key)] if !ok { return fmt.Errorf("parameter %s not registered", key) @@ -101,7 +100,7 @@ func (s Subspace) Validate(ctx sdk.Context, key []byte, value interface{}) error // Get queries for a parameter by key from the Subspace's KVStore and sets the // value to the provided pointer. If the value does not exist, it will panic. -func (s Subspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { +func (s Subspace) Get(ctx sdk.Context, key []byte, ptr any) { s.checkType(key, ptr) store := s.kvStore(ctx) @@ -115,7 +114,7 @@ func (s Subspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { // GetIfExists queries for a parameter by key from the Subspace's KVStore and // sets the value to the provided pointer. If the value does not exist, it will // perform a no-op. -func (s Subspace) GetIfExists(ctx sdk.Context, key []byte, ptr interface{}) { +func (s Subspace) GetIfExists(ctx sdk.Context, key []byte, ptr any) { store := s.kvStore(ctx) bz := store.Get(key) if bz == nil { @@ -165,7 +164,7 @@ func (s Subspace) Modified(ctx sdk.Context, key []byte) bool { } // checkType verifies that the provided key and value are comptable and registered. -func (s Subspace) checkType(key []byte, value interface{}) { +func (s Subspace) checkType(key []byte, value any) { attr, ok := s.table.m[string(key)] if !ok { panic(fmt.Sprintf("parameter %s not registered", key)) @@ -186,7 +185,7 @@ func (s Subspace) checkType(key []byte, value interface{}) { // been registered. It will panic if the parameter type has not been registered // or if the value cannot be encoded. A change record is also set in the Subspace's // transient KVStore to mark the parameter as modified. -func (s Subspace) Set(ctx sdk.Context, key []byte, value interface{}) { +func (s Subspace) Set(ctx sdk.Context, key []byte, value any) { s.checkType(key, value) store := s.kvStore(ctx) @@ -279,7 +278,7 @@ type ReadOnlySubspace struct { } // Get delegates a read-only Get call to the Subspace. -func (ros ReadOnlySubspace) Get(ctx sdk.Context, key []byte, ptr interface{}) { +func (ros ReadOnlySubspace) Get(ctx sdk.Context, key []byte, ptr any) { ros.s.Get(ctx, key, ptr) } diff --git a/x/protocolpool/keeper/keeper_test.go b/x/protocolpool/keeper/keeper_test.go index 724fb18b6a..7be6bd1844 100644 --- a/x/protocolpool/keeper/keeper_test.go +++ b/x/protocolpool/keeper/keeper_test.go @@ -147,7 +147,7 @@ func (suite *KeeperTestSuite) TestGetAllContinuousFunds() { totalFunds := 10 // Insert a number of funds. - for i := 0; i < totalFunds; i++ { + for i := range totalFunds { accAddr := sdk.AccAddress(fmt.Sprintf("ao%d__________________", i)) fund := types.ContinuousFund{ diff --git a/x/simulation/log.go b/x/simulation/log.go index cd0a77c86a..0e9278dcc5 100644 --- a/x/simulation/log.go +++ b/x/simulation/log.go @@ -47,7 +47,7 @@ func (lw *StandardLogWriter) PrintLogs() { f := createLogFile(lw.Seed) defer f.Close() - for i := 0; i < len(lw.OpEntries); i++ { + for i := range lw.OpEntries { writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal()) _, err := f.WriteString(writeEntry) if err != nil { diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 35a8df0e79..ec58ece3f1 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -144,7 +144,7 @@ func (ops WeightedOperations) getSelectOpFn() simulation.SelectOpFn { return func(r *rand.Rand) simulation.Operation { x := r.Intn(totalOpWeight) - for i := 0; i < len(ops); i++ { + for i := range ops { if x <= ops[i].Weight() { return ops[i].Op() } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index d6236f1f7f..5ee761630f 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -323,14 +323,14 @@ func createBlockSimulator(tb testing.TB, printProgress bool, w io.Writer, params // Predetermine the blocksize slice so that we can do things like block // out certain operations without changing the ops that follow. - for i := 0; i < blocksize; i++ { + for range blocksize { opAndRz = append(opAndRz, opAndR{ op: selectOp(r), rand: r, }) } - for i := 0; i < blocksize; i++ { + for i := range blocksize { // NOTE: the Rand 'r' should not be used here. opAndR := opAndRz[i] op, r2 := opAndR.op, opAndR.rand @@ -387,7 +387,7 @@ func runQueuedOperations( allFutureOps = make([]simulation.FutureOperation, 0) numOpsRan = len(queuedOp) - for i := 0; i < numOpsRan; i++ { + for i := range numOpsRan { opMsg, futureOps, err := queuedOp[i](r, app, ctx, accounts, chainID) if len(futureOps) > 0 { allFutureOps = append(allFutureOps, futureOps...) diff --git a/x/simulation/transition_matrix.go b/x/simulation/transition_matrix.go index 9e2c69c066..5bbf5a7a23 100644 --- a/x/simulation/transition_matrix.go +++ b/x/simulation/transition_matrix.go @@ -23,7 +23,7 @@ type TransitionMatrix struct { // TODO: Provide example usage func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error) { n := len(weights) - for i := 0; i < n; i++ { + for i := range n { if len(weights[i]) != n { return TransitionMatrix{}, fmt.Errorf("transition matrix: non-square matrix provided, error on row %d", i) @@ -32,8 +32,8 @@ func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error totals := make([]int, n) - for row := 0; row < n; row++ { - for col := 0; col < n; col++ { + for row := range n { + for col := range n { totals[col] += weights[row][col] } } @@ -45,7 +45,7 @@ func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error // provided in the transition matrix. func (t TransitionMatrix) NextState(r *rand.Rand, i int) int { randNum := r.Intn(t.totals[i]) - for row := 0; row < t.n; row++ { + for row := range t.n { if randNum < t.weights[row][i] { return row } @@ -62,13 +62,13 @@ func GetMemberOfInitialState(r *rand.Rand, weights []int) int { n := len(weights) total := 0 - for i := 0; i < n; i++ { + for i := range n { total += weights[i] } randNum := r.Intn(total) - for state := 0; state < n; state++ { + for state := range n { if randNum < weights[state] { return state } diff --git a/x/simulation/util.go b/x/simulation/util.go index e9bc2335df..80085f103a 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -53,7 +53,7 @@ func getBlockSize(r *rand.Rand, params Params, lastBlockSizeState, avgBlockSize return state, blockSize } -func mustMarshalJSONIndent(o interface{}) []byte { +func mustMarshalJSONIndent(o any) []byte { bz, err := json.MarshalIndent(o, "", " ") if err != nil { panic(fmt.Sprintf("failed to JSON encode: %s", err)) diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 7c2a6b5d9b..584ed8493d 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -29,7 +29,7 @@ type BankKeeper interface { type ParamSubspace interface { HasKeyTable() bool WithKeyTable(table paramtypes.KeyTable) paramtypes.Subspace - Get(ctx sdk.Context, key []byte, ptr interface{}) + Get(ctx sdk.Context, key []byte, ptr any) GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) SetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) } diff --git a/x/slashing/types/params.go b/x/slashing/types/params.go index 2003922d6d..d878d135bb 100644 --- a/x/slashing/types/params.go +++ b/x/slashing/types/params.go @@ -64,7 +64,7 @@ func (p Params) Validate() error { return nil } -func validateSignedBlocksWindow(i interface{}) error { +func validateSignedBlocksWindow(i any) error { v, ok := i.(int64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -77,7 +77,7 @@ func validateSignedBlocksWindow(i interface{}) error { return nil } -func validateMinSignedPerWindow(i interface{}) error { +func validateMinSignedPerWindow(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -96,7 +96,7 @@ func validateMinSignedPerWindow(i interface{}) error { return nil } -func validateDowntimeJailDuration(i interface{}) error { +func validateDowntimeJailDuration(i any) error { v, ok := i.(time.Duration) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -109,7 +109,7 @@ func validateDowntimeJailDuration(i interface{}) error { return nil } -func validateSlashFractionDoubleSign(i interface{}) error { +func validateSlashFractionDoubleSign(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -128,7 +128,7 @@ func validateSlashFractionDoubleSign(i interface{}) error { return nil } -func validateSlashFractionDowntime(i interface{}) error { +func validateSlashFractionDowntime(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/staking/bench_test.go b/x/staking/bench_test.go index 3d61ee4922..3d83f81a47 100644 --- a/x/staking/bench_test.go +++ b/x/staking/bench_test.go @@ -30,7 +30,7 @@ func benchmarkValidateGenesis(b *testing.B, n int) { validators := make([]types.Validator, 0, n) addressL, pubKeyL := makeRandomAddressesAndPublicKeys(n) - for i := 0; i < n; i++ { + for i := range n { addr, pubKey := addressL[i], pubKeyL[i] validator := testutil.NewValidator(b, addr, pubKey) ni := int64(i + 1) @@ -50,7 +50,7 @@ func benchmarkValidateGenesis(b *testing.B, n int) { } func makeRandomAddressesAndPublicKeys(n int) (accL []sdk.ValAddress, pkL []*ed25519.PubKey) { - for i := 0; i < n; i++ { + for range n { pk := ed25519.GenPrivKey().PubKey().(*ed25519.PubKey) pkL = append(pkL, pk) accL = append(accL, sdk.ValAddress(pk.Address())) diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index 9fe6811321..cc85971e60 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -61,7 +61,7 @@ func (s *CLITestSuite) SetupSuite() { s.clientCtx = ctxGen() s.addrs = make([]sdk.AccAddress, 0) - for i := 0; i < 3; i++ { + for range 3 { k, _, err := s.clientCtx.Keyring.NewMnemonic("NewValidator", keyring.English, sdk.FullFundraiserPath, keyring.DefaultBIP39Passphrase, hd.Secp256k1) s.Require().NoError(err) diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 1d4cd64e4b..9feed178b2 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -54,7 +54,7 @@ func ValidateGenesis(data *types.GenesisState) error { func validateGenesisStateValidators(validators []types.Validator) error { addrMap := make(map[string]bool, len(validators)) - for i := 0; i < len(validators); i++ { + for i := range validators { val := validators[i] consPk, err := val.ConsPubKey() if err != nil { diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index cb7964bb87..41a8762894 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -109,7 +109,7 @@ func (s *KeeperTestSuite) TestDelegation() { require.NoError(err) require.Equal(3, len(resVals.Validators)) - for i := 0; i < 3; i++ { + for i := range 3 { resVal, err := keeper.GetDelegatorValidator(ctx, addrDels[0], valAddrs[i]) require.Nil(err) require.Equal(valAddrs[i].String(), resVal.GetOperator()) diff --git a/x/staking/migrations/v3/json_test.go b/x/staking/migrations/v3/json_test.go index c111f36651..b72a91d17c 100644 --- a/x/staking/migrations/v3/json_test.go +++ b/x/staking/migrations/v3/json_test.go @@ -28,7 +28,7 @@ func TestMigrateJSON(t *testing.T) { require.NoError(t, err) // Indent the JSON bz correctly. - var jsonObj map[string]interface{} + var jsonObj map[string]any err = json.Unmarshal(bz, &jsonObj) require.NoError(t, err) indentedBz, err := json.MarshalIndent(jsonObj, "", "\t") diff --git a/x/staking/migrations/v3/store.go b/x/staking/migrations/v3/store.go index 6cb6c62631..5142b95f2e 100644 --- a/x/staking/migrations/v3/store.go +++ b/x/staking/migrations/v3/store.go @@ -16,7 +16,7 @@ type subspace interface { GetParamSet(ctx sdk.Context, ps paramtypes.ParamSet) HasKeyTable() bool WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace - Set(ctx sdk.Context, key []byte, value interface{}) + Set(ctx sdk.Context, key []byte, value any) } // MigrateStore performs in-place store migrations from v0.43/v0.44/v0.45 to v0.46. diff --git a/x/staking/migrations/v5/migrations_test.go b/x/staking/migrations/v5/migrations_test.go index ef9ca6e8d7..6d00e80687 100644 --- a/x/staking/migrations/v5/migrations_test.go +++ b/x/staking/migrations/v5/migrations_test.go @@ -43,7 +43,7 @@ func TestHistoricalKeysMigration(t *testing.T) { // random cases seed := time.Now().UnixNano() r := rand.New(rand.NewSource(seed)) - for i := 0; i < 10; i++ { + for range 10 { height := r.Intn(math.MaxInt32-2) + 2 testCases[int64(height)] = testCase{} diff --git a/x/staking/simulation/genesis.go b/x/staking/simulation/genesis.go index 420342be7b..da626a8139 100644 --- a/x/staking/simulation/genesis.go +++ b/x/staking/simulation/genesis.go @@ -63,7 +63,7 @@ func RandomizedGenState(simState *module.SimulationState) { valAddrs := make([]sdk.ValAddress, simState.NumBonded) - for i := 0; i < int(simState.NumBonded); i++ { + for i := range int(simState.NumBonded) { valAddr := sdk.ValAddress(simState.Accounts[i].Address) valAddrs[i] = valAddr diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 9687b20648..3cbd233a11 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -107,7 +107,7 @@ func (p Params) Validate() error { return nil } -func validateUnbondingTime(i interface{}) error { +func validateUnbondingTime(i any) error { v, ok := i.(time.Duration) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -120,7 +120,7 @@ func validateUnbondingTime(i interface{}) error { return nil } -func validateMaxValidators(i interface{}) error { +func validateMaxValidators(i any) error { v, ok := i.(uint32) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -133,7 +133,7 @@ func validateMaxValidators(i interface{}) error { return nil } -func validateMaxEntries(i interface{}) error { +func validateMaxEntries(i any) error { v, ok := i.(uint32) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -146,7 +146,7 @@ func validateMaxEntries(i interface{}) error { return nil } -func validateHistoricalEntries(i interface{}) error { +func validateHistoricalEntries(i any) error { _, ok := i.(uint32) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -155,7 +155,7 @@ func validateHistoricalEntries(i interface{}) error { return nil } -func validateBondDenom(i interface{}) error { +func validateBondDenom(i any) error { v, ok := i.(string) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -172,7 +172,7 @@ func validateBondDenom(i interface{}) error { return nil } -func ValidatePowerReduction(i interface{}) error { +func ValidatePowerReduction(i any) error { v, ok := i.(math.Int) if !ok { return fmt.Errorf("invalid parameter type: %T", i) @@ -185,7 +185,7 @@ func ValidatePowerReduction(i interface{}) error { return nil } -func validateMinCommissionRate(i interface{}) error { +func validateMinCommissionRate(i any) error { v, ok := i.(math.LegacyDec) if !ok { return fmt.Errorf("invalid parameter type: %T", i) diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index ea0bc0e942..09f6f15234 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -261,7 +261,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { copy(sortedVals, vals) // Randomly shuffle validators, sort, and check it is equal to original sort - for i := 0; i < 10; i++ { + for range 10 { rand.Shuffle(10, func(i, j int) { vals[i], vals[j] = vals[j], vals[i] }) @@ -283,7 +283,7 @@ func TestValidatorsSortCometBFT(t *testing.T) { vals[i].Tokens = math.NewInt(rand.Int63()) } // create some validators with the same power - for i := 0; i < 10; i++ { + for i := range 10 { vals[i].Tokens = math.NewInt(1000000) } @@ -308,7 +308,7 @@ func TestValidatorToCmt(t *testing.T) { vals := types.Validators{} expected := make([]*cmttypes.Validator, 10) - for i := 0; i < 10; i++ { + for i := range 10 { pk := ed25519.GenPrivKey().PubKey() val := newValidator(t, sdk.ValAddress(pk.Address()), pk) val.Status = types.Bonded