From 7d23bc6a1c4c97a98ab2662443d2ca40dec1adc1 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 7 Mar 2024 20:58:45 +0530 Subject: [PATCH 01/57] fix(query_request_test):Refactor query tests to use key instead of IDs The test cases in several query modules have been refactored. The order, meta, asset, and maintainer modules now use keys instead of IDs for test cases. This involves updating the relevant fields and test data. The change enhances code consistency and test coverage for the application. --- x/assets/queries/asset/query_request_test.go | 42 +++++------ .../queries/maintainer/query_request_test.go | 49 ++++++------- x/metas/queries/meta/query_request_test.go | 42 +++++------ x/orders/queries/order/query_request_test.go | 41 +++++------ x/splits/queries/supply/query_keeper_test.go | 69 ++++++++++--------- 5 files changed, 128 insertions(+), 115 deletions(-) diff --git a/x/assets/queries/asset/query_request_test.go b/x/assets/queries/asset/query_request_test.go index e39e33ee5..dfabcaba8 100644 --- a/x/assets/queries/asset/query_request_test.go +++ b/x/assets/queries/asset/query_request_test.go @@ -4,9 +4,10 @@ package asset import ( - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/helpers/base" + "github.com/AssetMantle/modules/helpers/constants" + "github.com/AssetMantle/modules/x/assets/key" baseData "github.com/AssetMantle/schema/go/data/base" "github.com/AssetMantle/schema/go/ids" baseIDs "github.com/AssetMantle/schema/go/ids/base" @@ -16,10 +17,8 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/spf13/viper" "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" - "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/helpers/constants" + "reflect" + "testing" ) var ( @@ -27,6 +26,7 @@ var ( mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) classificationID = baseIDs.NewClassificationID(immutables, mutables) testAssetID = baseIDs.NewAssetID(classificationID, immutables).(*baseIDs.AssetID) + testKey = key.NewKey(testAssetID).(*key.Key) ) func Test_newQueryRequest(t *testing.T) { @@ -76,7 +76,7 @@ func Test_queryRequest_Decode(t *testing.T) { encodedQuery1, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(baseIDs.PrototypeAssetID().(*baseIDs.AssetID))) require.NoError(t, err) type fields struct { - AssetID *baseIDs.AssetID + Key *key.Key } type args struct { bytes []byte @@ -88,13 +88,13 @@ func Test_queryRequest_Decode(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testAssetID}, args{encodedQuery}, newQueryRequest(testAssetID), false}, - {"+ve", fields{baseIDs.PrototypeAssetID().(*baseIDs.AssetID)}, args{encodedQuery1}, newQueryRequest(baseIDs.PrototypeAssetID().(*baseIDs.AssetID)), false}, + {"+ve", fields{testKey}, args{encodedQuery}, newQueryRequest(testAssetID), false}, + {"+ve", fields{key.NewKey(baseIDs.PrototypeAssetID()).(*key.Key)}, args{encodedQuery1}, newQueryRequest(baseIDs.PrototypeAssetID().(*baseIDs.AssetID)), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - AssetID: tt.fields.AssetID, + Key: tt.fields.Key, } got, err := queryRequest.Decode(tt.args.bytes) if (err != nil) != tt.wantErr { @@ -114,7 +114,7 @@ func Test_queryRequest_Encode(t *testing.T) { encodedQuery1, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(baseIDs.PrototypeAssetID().(*baseIDs.AssetID))) require.NoError(t, err) type fields struct { - AssetID *baseIDs.AssetID + Key *key.Key } tests := []struct { name string @@ -122,13 +122,13 @@ func Test_queryRequest_Encode(t *testing.T) { want []byte wantErr bool }{ - {"+ve", fields{testAssetID}, encodedQuery, false}, - {"+ve with nil", fields{baseIDs.PrototypeAssetID().(*baseIDs.AssetID)}, encodedQuery1, false}, + {"+ve", fields{testKey}, encodedQuery, false}, + {"+ve with nil", fields{key.NewKey(baseIDs.PrototypeAssetID().(*baseIDs.AssetID)).(*key.Key)}, encodedQuery1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - AssetID: tt.fields.AssetID, + Key: tt.fields.Key, } got, err := queryRequest.Encode() if (err != nil) != tt.wantErr { @@ -147,7 +147,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { viper.Set(constants.AssetID.GetName(), testAssetID.AsString()) type fields struct { - AssetID *baseIDs.AssetID + Key *key.Key } type args struct { cliCommand helpers.CLICommand @@ -160,12 +160,12 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testAssetID}, args{cliCommand, base.TestClientContext}, newQueryRequest(testAssetID), false}, + {"+ve", fields{testKey}, args{cliCommand, base.TestClientContext}, newQueryRequest(testAssetID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { qu := &QueryRequest{ - AssetID: tt.fields.AssetID, + Key: tt.fields.Key, } got, err := qu.FromCLI(tt.args.cliCommand, tt.args.context) if (err != nil) != tt.wantErr { @@ -181,19 +181,19 @@ func Test_queryRequest_FromCLI(t *testing.T) { func Test_queryRequest_Validate(t *testing.T) { type fields struct { - AssetID *baseIDs.AssetID + Key *key.Key } tests := []struct { name string fields fields wantErr bool }{ - {"+ve", fields{testAssetID}, false}, + {"+ve", fields{testKey}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - AssetID: tt.fields.AssetID, + Key: tt.fields.Key, } if err := queryRequest.Validate(); (err != nil) != tt.wantErr { t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) diff --git a/x/maintainers/queries/maintainer/query_request_test.go b/x/maintainers/queries/maintainer/query_request_test.go index b1ece31f4..ddbbb5dda 100644 --- a/x/maintainers/queries/maintainer/query_request_test.go +++ b/x/maintainers/queries/maintainer/query_request_test.go @@ -4,6 +4,7 @@ package maintainer import ( + "github.com/AssetMantle/modules/x/maintainers/key" "reflect" "testing" @@ -20,7 +21,9 @@ import ( var ( testMaintainerID, _ = createTestData() + testKey = key.NewKey(testMaintainerID).(*key.Key) testMaintainerID1 = baseIDs.PrototypeMaintainerID().(*baseIDs.MaintainerID) + testKey1 = key.NewKey(testMaintainerID1).(*key.Key) ) func Test_newQueryRequest(t *testing.T) { @@ -32,8 +35,8 @@ func Test_newQueryRequest(t *testing.T) { args args want helpers.QueryRequest }{ - {"+ve", args{testMaintainerID}, &QueryRequest{testMaintainerID}}, - {"+ve with nil", args{testMaintainerID1}, &QueryRequest{testMaintainerID1}}, + {"+ve", args{testMaintainerID}, &QueryRequest{testKey}}, + {"+ve with nil", args{testMaintainerID1}, &QueryRequest{testKey1}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -53,8 +56,8 @@ func Test_queryRequestFromInterface(t *testing.T) { args args want helpers.QueryRequest }{ - {"+ve", args{newQueryRequest(testMaintainerID)}, &QueryRequest{testMaintainerID}}, - {"+ve with nil", args{newQueryRequest(testMaintainerID1)}, &QueryRequest{testMaintainerID1}}, + {"+ve", args{newQueryRequest(testMaintainerID)}, &QueryRequest{testKey}}, + {"+ve with nil", args{newQueryRequest(testMaintainerID1)}, &QueryRequest{testKey1}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -66,12 +69,12 @@ func Test_queryRequestFromInterface(t *testing.T) { } func Test_queryRequest_Decode(t *testing.T) { - encodedQuery, err := (&QueryRequest{testMaintainerID}).Encode() + encodedQuery, err := (&QueryRequest{testKey}).Encode() require.NoError(t, err) - encodedQuery1, err := (&QueryRequest{testMaintainerID1}).Encode() + encodedQuery1, err := (&QueryRequest{testKey1}).Encode() require.NoError(t, err) type fields struct { - MaintainerID *baseIDs.MaintainerID + key *key.Key } type args struct { bytes []byte @@ -83,13 +86,13 @@ func Test_queryRequest_Decode(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testMaintainerID}, args{encodedQuery}, &QueryRequest{testMaintainerID}, false}, - {"+ve", fields{testMaintainerID1}, args{encodedQuery1}, &QueryRequest{testMaintainerID1}, false}, + {"+ve", fields{testKey}, args{encodedQuery}, &QueryRequest{testKey}, false}, + {"+ve", fields{testKey1}, args{encodedQuery1}, &QueryRequest{testKey1}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - MaintainerID: tt.fields.MaintainerID, + Key: tt.fields.key, } got, err := queryRequest.Decode(tt.args.bytes) if (err != nil) != tt.wantErr { @@ -104,12 +107,12 @@ func Test_queryRequest_Decode(t *testing.T) { } func Test_queryRequest_Encode(t *testing.T) { - encodedQuery, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{testMaintainerID}) + encodedQuery, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{testKey}) require.NoError(t, err) - encodedQuery1, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{testMaintainerID1}) + encodedQuery1, err := base.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{testKey1}) require.NoError(t, err) type fields struct { - MaintainerID *baseIDs.MaintainerID + key *key.Key } tests := []struct { name string @@ -117,13 +120,13 @@ func Test_queryRequest_Encode(t *testing.T) { want []byte wantErr bool }{ - {"+ve", fields{testMaintainerID}, encodedQuery, false}, - {"+ve with nil", fields{testMaintainerID1}, encodedQuery1, false}, + {"+ve", fields{testKey}, encodedQuery, false}, + {"+ve with nil", fields{testKey1}, encodedQuery1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - MaintainerID: tt.fields.MaintainerID, + Key: tt.fields.key, } got, err := queryRequest.Encode() if (err != nil) != tt.wantErr { @@ -141,7 +144,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.MaintainerID}) viper.Set(constants.MaintainerID.GetName(), testMaintainerID.AsString()) type fields struct { - MaintainerID *baseIDs.MaintainerID + key *key.Key } type args struct { cliCommand helpers.CLICommand @@ -154,12 +157,12 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testMaintainerID}, args{cliCommand, client.Context{}}, &QueryRequest{testMaintainerID}, false}, + {"+ve", fields{testKey}, args{cliCommand, client.Context{}}, &QueryRequest{testKey}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { qu := &QueryRequest{ - MaintainerID: tt.fields.MaintainerID, + Key: tt.fields.key, } got, err := qu.FromCLI(tt.args.cliCommand, tt.args.context) if (err != nil) != tt.wantErr { @@ -175,20 +178,20 @@ func Test_queryRequest_FromCLI(t *testing.T) { func Test_queryRequest_Validate(t *testing.T) { type fields struct { - MaintainerID *baseIDs.MaintainerID + key *key.Key } tests := []struct { name string fields fields wantErr bool }{ - {"+ve", fields{testMaintainerID}, false}, - {"+ve with nil", fields{testMaintainerID1}, false}, + {"+ve", fields{testKey}, false}, + {"+ve with nil", fields{testKey1}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - MaintainerID: tt.fields.MaintainerID, + Key: tt.fields.key, } if err := queryRequest.Validate(); (err != nil) != tt.wantErr { t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) diff --git a/x/metas/queries/meta/query_request_test.go b/x/metas/queries/meta/query_request_test.go index b035f89ee..2d8d69773 100644 --- a/x/metas/queries/meta/query_request_test.go +++ b/x/metas/queries/meta/query_request_test.go @@ -4,6 +4,7 @@ package meta import ( + "github.com/AssetMantle/modules/x/metas/key" "reflect" "testing" @@ -20,7 +21,8 @@ import ( ) var ( - testDataID = baseIDs.GenerateDataID(baseData.NewStringData("Data")).(*baseIDs.DataID) + testDataID = baseData.NewStringData("testData").GetID() + testKey = key.NewKey(testDataID).(*key.Key) ) func Test_newQueryRequest(t *testing.T) { @@ -32,8 +34,8 @@ func Test_newQueryRequest(t *testing.T) { args args want helpers.QueryRequest }{ - {"+ve with nil", args{baseIDs.PrototypeDataID().(*baseIDs.DataID)}, &QueryRequest{baseIDs.PrototypeDataID().(*baseIDs.DataID)}}, - {"+ve", args{testDataID}, &QueryRequest{testDataID}}, + {"+ve with nil", args{baseIDs.PrototypeDataID().(*baseIDs.DataID)}, &QueryRequest{key.NewKey(baseIDs.PrototypeDataID().(*baseIDs.DataID)).(*key.Key)}}, + {"+ve", args{testDataID}, &QueryRequest{testKey}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -53,7 +55,7 @@ func Test_queryRequestFromInterface(t *testing.T) { args args want helpers.QueryRequest }{ - {"+ve", args{newQueryRequest(testDataID)}, &QueryRequest{testDataID}}, + {"+ve", args{newQueryRequest(testDataID)}, &QueryRequest{key.NewKey(testDataID).(*key.Key)}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -70,7 +72,7 @@ func Test_queryRequest_Decode(t *testing.T) { encodedQuery1, err := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(baseIDs.PrototypeDataID().(*baseIDs.DataID))) require.NoError(t, err) type fields struct { - DataID *baseIDs.DataID + Key *key.Key } type args struct { bytes []byte @@ -82,13 +84,13 @@ func Test_queryRequest_Decode(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testDataID}, args{encodedQuery}, newQueryRequest(testDataID), false}, - {"+ve with nil", fields{baseIDs.PrototypeDataID().(*baseIDs.DataID)}, args{encodedQuery1}, newQueryRequest(baseIDs.PrototypeDataID().(*baseIDs.DataID)), false}, + {"+ve", fields{testKey}, args{encodedQuery}, newQueryRequest(testDataID), false}, + {"+ve with nil", fields{key.NewKey(baseIDs.PrototypeDataID()).(*key.Key)}, args{encodedQuery1}, newQueryRequest(baseIDs.PrototypeDataID().(*baseIDs.DataID)), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - DataID: tt.fields.DataID, + Key: tt.fields.Key, } got, err := queryRequest.Decode(tt.args.bytes) if (err != nil) != tt.wantErr { @@ -108,7 +110,7 @@ func Test_queryRequest_Encode(t *testing.T) { encodedQuery1, err := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(baseIDs.PrototypeDataID().(*baseIDs.DataID))) require.NoError(t, err) type fields struct { - DataID *baseIDs.DataID + Key *key.Key } tests := []struct { name string @@ -116,13 +118,13 @@ func Test_queryRequest_Encode(t *testing.T) { want []byte wantErr bool }{ - {"+ve", fields{testDataID}, encodedQuery, false}, - {"+ve with nil", fields{baseIDs.PrototypeDataID().(*baseIDs.DataID)}, encodedQuery1, false}, + {"+ve", fields{testKey}, encodedQuery, false}, + {"+ve with nil", fields{key.NewKey(baseIDs.PrototypeDataID()).(*key.Key)}, encodedQuery1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - DataID: tt.fields.DataID, + Key: tt.fields.Key, } got, err := queryRequest.Encode() if (err != nil) != tt.wantErr { @@ -138,9 +140,9 @@ func Test_queryRequest_Encode(t *testing.T) { func Test_queryRequest_FromCLI(t *testing.T) { cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.DataID}) - viper.Set(constants.DataID.GetName(), testDataID.AsString()) + viper.Set(constants.DataID.GetName(), testKey) type fields struct { - DataID *baseIDs.DataID + Key *key.Key } type args struct { cliCommand helpers.CLICommand @@ -153,12 +155,12 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testDataID}, args{cliCommand, client.Context{}}, newQueryRequest(testDataID), false}, + {"+ve", fields{testKey}, args{cliCommand, client.Context{}}, newQueryRequest(testDataID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { qu := &QueryRequest{ - DataID: tt.fields.DataID, + Key: tt.fields.Key, } got, err := qu.FromCLI(tt.args.cliCommand, tt.args.context) if (err != nil) != tt.wantErr { @@ -174,20 +176,20 @@ func Test_queryRequest_FromCLI(t *testing.T) { func Test_queryRequest_Validate(t *testing.T) { type fields struct { - DataID *baseIDs.DataID + Key *key.Key } tests := []struct { name string fields fields wantErr bool }{ - {"+ve", fields{testDataID}, false}, - {"+ve", fields{baseIDs.PrototypeDataID().(*baseIDs.DataID)}, false}, + {"+ve", fields{testKey}, false}, + {"+ve", fields{key.NewKey(baseIDs.PrototypeDataID()).(*key.Key)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - DataID: tt.fields.DataID, + Key: tt.fields.Key, } if err := queryRequest.Validate(); (err != nil) != tt.wantErr { t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) diff --git a/x/orders/queries/order/query_request_test.go b/x/orders/queries/order/query_request_test.go index 8c6bfd9e3..86cebd493 100644 --- a/x/orders/queries/order/query_request_test.go +++ b/x/orders/queries/order/query_request_test.go @@ -4,6 +4,7 @@ package order import ( + "github.com/AssetMantle/modules/x/orders/key" "reflect" "testing" @@ -23,13 +24,13 @@ import ( ) var ( - immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) - mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) testClassificationID = baseIDs.NewClassificationID(immutables, mutables).(*baseIDs.ClassificationID) - testFromID = baseIDs.NewIdentityID(testClassificationID, immutables).(*baseIDs.IdentityID) testOrderID = baseIDs.NewOrderID(testClassificationID, immutables).(*baseIDs.OrderID) + testKey = key.NewKey(testOrderID).(*key.Key) testOrderID1 = baseIDs.PrototypeOrderID().(*baseIDs.OrderID) + testKey1 = key.NewKey(testOrderID1).(*key.Key) ) func Test_newQueryRequest(t *testing.T) { @@ -62,8 +63,8 @@ func Test_queryRequestFromInterface(t *testing.T) { args args want helpers.QueryRequest }{ - {"+ve", args{newQueryRequest(testOrderID)}, &QueryRequest{testOrderID}}, - {"+ve with nil", args{newQueryRequest(testOrderID1)}, &QueryRequest{testOrderID1}}, + {"+ve", args{newQueryRequest(testOrderID)}, &QueryRequest{testKey}}, + {"+ve with nil", args{newQueryRequest(testOrderID1)}, &QueryRequest{testKey1}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -80,7 +81,7 @@ func Test_queryRequest_Decode(t *testing.T) { encodedReq1, err1 := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(testOrderID1)) require.NoError(t, err1) type fields struct { - OrderID *baseIDs.OrderID + Key *key.Key } type args struct { bytes []byte @@ -92,13 +93,13 @@ func Test_queryRequest_Decode(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testOrderID}, args{encodedReq}, newQueryRequest(testOrderID), false}, - {"+ve", fields{testOrderID1}, args{encodedReq1}, newQueryRequest(testOrderID1), false}, + {"+ve", fields{testKey}, args{encodedReq}, newQueryRequest(testOrderID), false}, + {"+ve", fields{testKey1}, args{encodedReq1}, newQueryRequest(testOrderID1), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - OrderID: tt.fields.OrderID, + Key: tt.fields.Key, } got, err := queryRequest.Decode(tt.args.bytes) if (err != nil) != tt.wantErr { @@ -118,7 +119,7 @@ func Test_queryRequest_Encode(t *testing.T) { encodedReq1, err1 := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(testOrderID1)) require.NoError(t, err1) type fields struct { - OrderID *baseIDs.OrderID + Key *key.Key } tests := []struct { name string @@ -126,13 +127,13 @@ func Test_queryRequest_Encode(t *testing.T) { want []byte wantErr bool }{ - {"+ve", fields{testOrderID}, encodedReq, false}, - {"+ve", fields{testOrderID1}, encodedReq1, false}, + {"+ve", fields{testKey}, encodedReq, false}, + {"+ve", fields{testKey1}, encodedReq1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - OrderID: tt.fields.OrderID, + Key: tt.fields.Key, } got, err := queryRequest.Encode() if (err != nil) != tt.wantErr { @@ -151,7 +152,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { viper.Set(constants.OrderID.GetName(), testOrderID.AsString()) type fields struct { - OrderID *baseIDs.OrderID + Key *key.Key } type args struct { cliCommand helpers.CLICommand @@ -164,12 +165,12 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testOrderID}, args{cliCommand, baseHelpers.TestClientContext}, newQueryRequest(testOrderID), false}, + {"+ve", fields{testKey}, args{cliCommand, baseHelpers.TestClientContext}, newQueryRequest(testOrderID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { qu := &QueryRequest{ - OrderID: tt.fields.OrderID, + Key: tt.fields.Key, } got, err := qu.FromCLI(tt.args.cliCommand, tt.args.context) if (err != nil) != tt.wantErr { @@ -185,19 +186,19 @@ func Test_queryRequest_FromCLI(t *testing.T) { func Test_queryRequest_Validate(t *testing.T) { type fields struct { - OrderID *baseIDs.OrderID + Key *key.Key } tests := []struct { name string fields fields wantErr bool }{ - {"+ve", fields{testOrderID}, false}, + {"+ve", fields{testKey}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryRequest := &QueryRequest{ - OrderID: tt.fields.OrderID, + Key: tt.fields.Key, } if err := queryRequest.Validate(); (err != nil) != tt.wantErr { t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) diff --git a/x/splits/queries/supply/query_keeper_test.go b/x/splits/queries/supply/query_keeper_test.go index f55815d3b..026d0891e 100644 --- a/x/splits/queries/supply/query_keeper_test.go +++ b/x/splits/queries/supply/query_keeper_test.go @@ -4,6 +4,7 @@ package supply import ( + "context" "fmt" "reflect" "testing" @@ -26,7 +27,6 @@ import ( "github.com/AssetMantle/modules/helpers" baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/splits/mappable" "github.com/AssetMantle/modules/x/splits/parameters" "github.com/AssetMantle/modules/x/splits/record" ) @@ -60,7 +60,7 @@ func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mappe err := commitMultiStore.LoadLatestVersion() require.Nil(t, err) - context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ + Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) @@ -68,7 +68,7 @@ func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mappe QueryKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.QueryKeeper), } - return context, keepers, Mapper, parameterManager + return Context, keepers, Mapper, parameterManager } func Test_keeperPrototype(t *testing.T) { @@ -87,68 +87,75 @@ func Test_keeperPrototype(t *testing.T) { } } -func Test_queryKeeper_Enquire(t *testing.T) { - context, keepers, Mapper, _ := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) - testAssetID := baseDocuments.NewCoinAsset("OwnerID").GetCoinAssetID() - testRate := sdkTypes.OneInt() - split := baseTypes.NewSplit(testOwnerIdentityID, testAssetID, testRate) - keepers.QueryKeeper.(queryKeeper).mapper.NewCollection(sdkTypes.WrapSDKContext(context)).Add(mappable.NewMappable(split)) +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, mapper, parameterManager := createTestInput(t) type fields struct { mapper helpers.Mapper } type args struct { - context sdkTypes.Context - queryRequest helpers.QueryRequest + mapper helpers.Mapper + in1 helpers.ParameterManager + in2 []interface{} } tests := []struct { name string fields fields args args - want helpers.QueryResponse + want helpers.Keeper }{ - {"+ve", fields{Mapper}, args{context, newQueryRequest(testAssetID)}, newQueryResponse(testRate)}, + {"+ve", fields{mapper}, args{mapper, parameterManager, []interface{}{}}, queryKeeper{mapper}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryKeeper := queryKeeper{ mapper: tt.fields.mapper, } - if got := queryKeeper.Enquire(sdkTypes.WrapSDKContext(tt.args.context), tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { - t.Errorf("Enquire() = %v, want %v", got, tt.want) + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) } }) } } -func Test_queryKeeper_Initialize(t *testing.T) { - _, _, mapper, parameterManager := createTestInput(t) +func Test_queryKeeper_Enquire(t *testing.T) { + Context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) + testAssetID := baseDocuments.NewCoinAsset("OwnerID").GetCoinAssetID() + testRate := sdkTypes.OneInt() + split := baseTypes.NewSplit(testRate) + keepers.QueryKeeper.(queryKeeper).mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(baseIDs.NewSplitID(testAssetID, testOwnerIdentityID), split)) + type fields struct { mapper helpers.Mapper } type args struct { - mapper helpers.Mapper - in1 helpers.ParameterManager - in2 []interface{} + context context.Context + queryRequest helpers.QueryRequest } tests := []struct { - name string - fields fields - args args - want helpers.Keeper + name string + fields fields + args args + want helpers.QueryResponse + wantErr bool }{ - {"+ve", fields{mapper}, args{mapper, parameterManager, []interface{}{}}, queryKeeper{mapper}}, + {"+ve", fields{Mapper}, args{Context.Context(), newQueryRequest(testAssetID)}, newQueryResponse(testRate), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { queryKeeper := queryKeeper{ mapper: tt.fields.mapper, } - if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) + got, err := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest) + if (err != nil) != tt.wantErr { + t.Errorf("Enquire() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() got = %v, want %v", got, tt.want) } }) } From 9532d8a1953f5757df061d64cccde368b97fa531 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 7 Mar 2024 20:59:38 +0530 Subject: [PATCH 02/57] chore: removing test cases generate with dated test case building methodologies --- helpers/base/collection_test.go | 53 ---- helpers/base/mapper_test.go | 56 ----- helpers/base/module_test.go | 122 --------- helpers/base/parameter_manager_test.go | 44 ---- helpers/base/query_test.go | 60 ----- helpers/base/transaction_test.go | 112 --------- utilities/rest/queuing/kafka_test.go | 63 ----- utilities/rest/queuing/kafka_types_test.go | 42 ---- .../classification/query_request_test.go | 215 ---------------- .../queries/identity/query_request_test.go | 237 ------------------ .../queries/balances/query_response_test.go | 26 -- x/splits/queries/split/query_response_test.go | 54 ---- 12 files changed, 1084 deletions(-) diff --git a/helpers/base/collection_test.go b/helpers/base/collection_test.go index fba9b6e3f..1944e7a61 100644 --- a/helpers/base/collection_test.go +++ b/helpers/base/collection_test.go @@ -2,56 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" -) - -func TestCollection(t *testing.T) { - context, storeKey, _ := test.SetupTest(t) - Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) - - // Initialize - Collection := collection{}.Initialize(context, Mapper).(collection) - require.Equal(t, reflect.TypeOf(Mapper), reflect.TypeOf(Collection.mapper)) - - // Add - collection1 := Collection.Add(base.NewMappable("test1", "value1")) - require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, collection1.Get()) - require.Nil(t, collection1.GetKey()) - - _ = Collection.Add(base.NewMappable("test2", "value2")) - _ = Collection.Add(base.NewMappable("test3", "value3")) - - // Mutate - Collection.Mutate(base.NewMappable("test2", "value3")) - require.Equal(t, base.NewMappable("test2", "value3"), Collection.Fetch(base.NewKey("test2")).GetMappable(base.NewKey("test2"))) - require.NotEqual(t, base.NewMappable("test2", "value2"), Collection.Fetch(base.NewKey("test2")).GetMappable(base.NewKey("test2"))) - - // GetAuxiliary - require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, Collection.Fetch(base.NewKey("test1")).Get()) - - // GetProperty - Collection.GetMappable(base.NewKey("test1")) - require.Equal(t, nil, Collection.GetMappable(base.NewKey("test1"))) - require.Equal(t, base.NewMappable("test1", "value1"), Collection.Fetch(base.NewKey("test1")).GetMappable(base.NewKey("test1"))) - - // GenerateKey - require.Equal(t, nil, Collection.GetKey()) - require.Equal(t, base.NewKey("test1"), Collection.Fetch(base.NewKey("test1")).GetKey()) - require.Equal(t, base.NewKey("test4"), Collection.Fetch(base.NewKey("test4")).GetKey()) - - // GetAuxiliary - Collection.Get() - require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, Collection.Fetch(base.NewKey("test1")).Get()) - - // Remove - Collection.Remove(base.NewMappable("test1", "value0")) - require.Equal(t, []helpers.Mappable(nil), Collection.Fetch(base.NewKey("test1")).Get()) - -} diff --git a/helpers/base/mapper_test.go b/helpers/base/mapper_test.go index a4604c27c..1944e7a61 100644 --- a/helpers/base/mapper_test.go +++ b/helpers/base/mapper_test.go @@ -2,59 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" -) - -func TestMapper(t *testing.T) { - context, storeKey, _ := test.SetupTest(t) - - // NewMapper - Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) - testMapper := Mapper.(mapper) - - // Initialize - require.Equal(t, storeKey, testMapper.kvStoreKey) - - // GetKVStoreKey - require.Equal(t, "test", testMapper.GetKVStoreKey().Name()) - - // NewCollection - require.Equal(t, reflect.TypeOf(collection{}), reflect.TypeOf(testMapper.NewCollection(context).(collection))) - require.Equal(t, testMapper.kvStoreKey.String(), testMapper.NewCollection(context).(collection).mapper.(mapper).kvStoreKey.String()) - require.Equal(t, context, testMapper.NewCollection(context).(collection).context) - - // Upsert - testMapper.Upsert(context, base.NewMappable("test1", "value1")) - testMapper.Upsert(context, base.NewMappable("test2", "value2")) - testMapper.Upsert(context, base.NewMappable("test3", "value3")) - - // Set - testMapper.Update(context, base.NewMappable("test2", "value3")) - - // Remove - testMapper.Delete(context, base.NewKey("test3")) - - // Read - require.Equal(t, base.NewMappable("test1", "value1"), testMapper.Read(context, base.NewKey("test1"))) - require.Equal(t, base.NewMappable("test2", "value3"), testMapper.Read(context, base.NewKey("test2"))) - require.Equal(t, nil, testMapper.Read(context, base.NewKey("test3"))) - - // Iterate - testMapper.Iterate(context, base.NewKey("test1"), func(mappable helpers.Mappable) bool { return false }) - testMapper.Iterate(context, base.NewKey("test3"), func(mappable helpers.Mappable) bool { return false }) - - // TODO: Test functionality without legacy amino - // Store Decoder - // require.Equal(t, "{test1 value1}\n{test1 value1}", testMapper.StoreDecoder(kv.Pair{ - // Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper..MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}, kv.Pair{ - // Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper.legacyAmino.MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}), - // ) - -} diff --git a/helpers/base/module_test.go b/helpers/base/module_test.go index 0185fc8f0..1944e7a61 100644 --- a/helpers/base/module_test.go +++ b/helpers/base/module_test.go @@ -2,125 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "encoding/json" - "math/rand" - "testing" - - baseData "github.com/AssetMantle/schema/go/data/base" - baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseParameters "github.com/AssetMantle/schema/go/parameters/base" - "github.com/AssetMantle/schema/go/properties/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - sdkModuleTypes "github.com/cosmos/cosmos-sdk/types/module" - paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/gorilla/mux" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - - "github.com/AssetMantle/modules/helpers" -) - -// TODO: Add grpc gateway handling for tests - -var auxiliariesPrototype = func() helpers.Auxiliaries { - return auxiliaries{[]helpers.Auxiliary{NewAuxiliary("testAuxiliary", baseTestUtilities.TestAuxiliaryKeeperPrototype)}} -} -var genesisPrototype = func() helpers.Genesis { - return baseTestUtilities.Prototype() -} -var mapperPrototype = func() helpers.Mapper { - return NewMapper(baseTestUtilities.KeyPrototype, baseTestUtilities.MappablePrototype) -} -var parameterManagerPrototype = func() helpers.ParameterManager { - return NewParameterManager("", NewValidatableParameter(baseParameters.NewParameter(base.NewMetaProperty(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"))), func(interface{}) error { return nil })) -} -var queriesPrototype = func() helpers.Queries { - return queries{[]helpers.Query{NewQuery("testQuery", "q", "testQuery", "test", baseTestUtilities.TestQueryRequestPrototype, - baseTestUtilities.TestQueryResponsePrototype, baseTestUtilities.TestQueryKeeperPrototype, nil, nil)}} -} -var simulatorPrototype = func() helpers.Simulator { return nil } -var transactionsPrototype = func() helpers.Transactions { - return transactions{[]helpers.Transaction{NewTransaction("TestMessage", "", "", baseTestUtilities.TestTransactionRequestPrototype, baseTestUtilities.TestMessagePrototype, - baseTestUtilities.TestTransactionKeeperPrototype, nil, nil)}} -} -var blockPrototype = func() helpers.Block { return baseTestUtilities.TestBlockPrototype() } - -func TestModule(t *testing.T) { - context, storeKey, transientStoreKey := test.SetupTest(t) - - codec := CodecPrototype() - - subspace := paramsTypes.NewSubspace(codec.GetProtoCodec(), codec.GetLegacyAmino(), storeKey, transientStoreKey, "test") // .WithKeyTable(parameterManagerPrototype().GetKeyTable()) - // subspace.SetParamSet(sdkTypes.UnwrapSDKContext(context), parameterManagerPrototype()) - Module := NewModule("test", 1, auxiliariesPrototype, blockPrototype, genesisPrototype, nil, - mapperPrototype, parameterManagerPrototype, queriesPrototype, simulatorPrototype, transactionsPrototype).Initialize(storeKey, subspace).(module) - - // AppModuleBasic - require.Equal(t, "test", Module.Name()) - - // RegisterLegacyAminoCodec - Module.RegisterLegacyAminoCodec(codec.GetLegacyAmino()) - - require.NotPanics(t, func() { - Module.DefaultGenesis(codec.GetProtoCodec()) - }) - - require.NotPanics(t, func() { - }) - require.Nil(t, Module.ValidateGenesis(codec.GetProtoCodec(), nil, Module.DefaultGenesis(codec.GetProtoCodec()))) - - router := mux.NewRouter() - require.NotPanics(t, func() { - Module.RegisterRESTRoutes(TestClientContext, router) - }) - - // GetTxCmd - require.Equal(t, "test", Module.GetTxCmd().Name()) - require.Equal(t, "test", Module.GetQueryCmd().Name()) - - // AppModule - require.NotPanics(t, func() { - Module.RegisterInvariants(nil) - }) - require.Equal(t, "test", Module.Route()) - - response, err := Module.Route().Handler()(sdkTypes.UnwrapSDKContext(context), baseTestUtilities.NewTestMessage(sdkTypes.AccAddress("addr"), "id")) - require.Nil(t, err) - require.NotNil(t, response) - - require.Equal(t, "test", Module.QuerierRoute()) - - encodedRequest, err := Module.queries.GetQuery("testQuery").(query).requestPrototype().Encode() - require.Nil(t, err) - - queryResponse, err := Module.LegacyQuerierHandler(codec.GetLegacyAmino())(sdkTypes.UnwrapSDKContext(context), []string{"testQuery"}, abciTypes.RequestQuery{Data: encodedRequest}) - require.Nil(t, err) - require.NotNil(t, queryResponse) - - require.NotPanics(t, func() { - Module.BeginBlock(sdkTypes.UnwrapSDKContext(context), abciTypes.RequestBeginBlock{}) - }) - endBlockResponse := Module.EndBlock(sdkTypes.UnwrapSDKContext(context), abciTypes.RequestEndBlock{}) - require.Equal(t, []abciTypes.ValidatorUpdate{}, endBlockResponse) - - require.NotPanics(t, func() { - Module.InitGenesis(sdkTypes.UnwrapSDKContext(context), codec.GetProtoCodec(), Module.DefaultGenesis(codec.GetProtoCodec())) - }) - - require.Equal(t, Module.DefaultGenesis(codec.GetProtoCodec()), Module.ExportGenesis(sdkTypes.UnwrapSDKContext(context), codec.GetProtoCodec())) - // AppModuleSimulation - require.Panics(t, func() { - Module.GenerateGenesisState(&sdkModuleTypes.SimulationState{}) - Module.ProposalContents(sdkModuleTypes.SimulationState{}) - Module.RandomizedParams(&rand.Rand{}) - Module.RegisterStoreDecoder(sdkTypes.StoreDecoderRegistry{}) - Module.WeightedOperations(sdkModuleTypes.SimulationState{}) - }) - - // types.Module - require.Equal(t, "testAuxiliary", Module.GetAuxiliary("testAuxiliary").GetName()) - _, err = Module.DecodeModuleTransactionRequest("TestMessage", json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) - require.Nil(t, err) -} diff --git a/helpers/base/parameter_manager_test.go b/helpers/base/parameter_manager_test.go index e89f0988e..1944e7a61 100644 --- a/helpers/base/parameter_manager_test.go +++ b/helpers/base/parameter_manager_test.go @@ -2,47 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "testing" - - baseData "github.com/AssetMantle/schema/go/data/base" - baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseParameters "github.com/AssetMantle/schema/go/parameters/base" - parametersSchema "github.com/AssetMantle/schema/go/parameters/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/require" -) - -func TestParameters(t *testing.T) { - context, storeKey, transientStoreKey, _ := test.SetupTest(t) - - codec := CodecPrototype() - - Parameter := baseParameters.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"), func(interface{}) error { return nil }) - parameters := []parametersSchema.Parameter{Parameter} - ParameterManager := NewParameterManager(parameters...).(*parameterManager) - subspace := paramsTypes.NewSubspace(codec.GetProtoCodec(), codec.GetLegacyAmino(), storeKey, transientStoreKey, "test").WithKeyTable(ParameterManager.GetKeyTable()) - subspace.SetParamSet(sdkTypes.UnwrapSDKContext(context), ParameterManager) - ParameterManager = ParameterManager.Initialize(subspace).(*parameterManager) - - require.NotNil(t, ParameterManager.ParamSetPairs()) - - require.NotNil(t, ParameterManager.GetKeyTable()) - - require.Equal(t, true, ParameterManager.Equal(ParameterManager)) - - require.Equal(t, true, ParameterManager.Get()[0].Equal(Parameter)) - require.Equal(t, `{"id":{"idString":"testParameter"},"data":{"value":"testData"}}`, ParameterManager.String()) - - err := ParameterManager.Validate() - require.Nil(t, err) - - require.NotPanics(t, func() { - ParameterManager.Fetch(context, baseIDs.NewStringID("testParameter")) - }) - - require.Equal(t, "testData123", ParameterManager.Mutate(context, - baseParameters.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData123"), func(interface{}) error { return nil })).Get(baseIDs.NewStringID("testParameter")).GetData().AsString()) -} diff --git a/helpers/base/query_test.go b/helpers/base/query_test.go index 43b4b1d54..1944e7a61 100644 --- a/helpers/base/query_test.go +++ b/helpers/base/query_test.go @@ -2,63 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" -) - -func TestQuery(t *testing.T) { - context, storeKey, _ := test.SetupTest(t) - Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) - Query := NewQuery("test", "t", "testQuery", "test", base.TestQueryRequestPrototype, - base.TestQueryResponsePrototype, base.TestQueryKeeperPrototype, - nil, - nil, - ).Initialize(Mapper, parameterManagerPrototype()).(query) - - require.Equal(t, nil, base.TestQueryKeeperPrototype().(base.TestQueryKeeper).Help(context, nil)) - require.Equal(t, nil, base.TestQueryRequestPrototype().Validate()) - require.Equal(t, false, base.TestQueryResponsePrototype().IsSuccessful()) - require.Equal(t, nil, base.TestQueryResponsePrototype().GetError()) - encodedResponse, err := base.TestQueryResponsePrototype().Encode() - require.Nil(t, err) - decodedResponse, err := base.TestQueryResponsePrototype().Decode(encodedResponse) - require.Nil(t, err) - require.Equal(t, Query.responsePrototype(), decodedResponse) - - // GetName - require.Equal(t, "test", Query.GetName()) - - // HandleQuery - encodedRequest, err := Query.requestPrototype().Encode() - require.Nil(t, err) - - _, err = Query.HandleQuery(context, abciTypes.RequestQuery{Data: encodedRequest}) - require.Nil(t, err) - - command := Query.Command() - command.SetArgs([]string{ - "test"}) - err = command.ParseFlags([]string{"--node", "tcp://localhost:26657"}) - require.Nil(t, err) - require.Equal(t, `ABCIQuery: Post failed: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused`, - command.ExecuteContext(context).Error()) - - // require.Equal(t, nil, command.ExecuteContext(context.Context())) - - // RESTQueryHandler - Query.RESTQueryHandler(TestClientContext) - - // RPC ERROR - testRequest1, err := http.NewRequest("GET", "/test", nil) - require.Nil(t, err) - responseRecorder := httptest.NewRecorder() - Query.RESTQueryHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest1) - require.Equal(t, responseRecorder.Code, http.StatusInternalServerError) - -} diff --git a/helpers/base/transaction_test.go b/helpers/base/transaction_test.go index eea5c043e..1944e7a61 100644 --- a/helpers/base/transaction_test.go +++ b/helpers/base/transaction_test.go @@ -2,115 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package base - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - sdkCodec "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" -) - -func TestTransaction(t *testing.T) { - context, storeKey, _ := test.SetupTest(t) - var legacyAmino = sdkCodec.NewLegacyAmino() - schemaCodec.RegisterLegacyAminoCodec(legacyAmino) - std.RegisterLegacyAminoCodec(legacyAmino) - legacyAmino.Seal() - Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) - Transaction := NewTransaction("test", "", "", base.TestTransactionRequestPrototype, base.TestMessagePrototype, - base.TestTransactionKeeperPrototype, nil, nil).InitializeKeeper(Mapper, parameterManagerPrototype()).(transaction) - require.Equal(t, "TestMessage", base.TestMessagePrototype().(*base.TestMessage).Route()) - require.NotNil(t, base.TestMessagePrototype().(*base.TestMessage).GetSignBytes()) - _, err := base.TestTransactionKeeperPrototype().Transact(context, nil) - require.Equal(t, nil, err) - - // GetName - require.Equal(t, "test", Transaction.GetName()) - - // DecodeTransactionRequest - message, err := Transaction.DecodeTransactionRequest(json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) - require.Equal(t, nil, err) - require.Equal(t, sdkTypes.AccAddress("addr"), message.GetSigners()[0]) - - // RegisterLegacyAminoCodec : No Panics - require.NotPanics(t, func() { Transaction.RegisterLegacyAminoCodec(legacyAmino) }) - - // Command : No Panics - command := Transaction.Command() - err = command.ParseFlags([]string{"--node", "tcp://localhost:26657"}) - require.Nil(t, err) - require.Equal(t, `ABCIQuery: Post failed: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused`, - command.ExecuteContext(context).Error()) - // HandleQuery - _, err = Transaction.HandleMessage(context, message.(helpers.Message)) - require.Nil(t, err) - - // RPC ERROR - request1 := legacyAmino.MustMarshalJSON(base.TransactionRequest{ - BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test"}, - ID: "ID", - }) - testRequest1, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request1)) - require.Nil(t, err) - responseRecorder := httptest.NewRecorder() - Transaction.RESTRequestHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest1) - require.Equal(t, `{"error":"ABCIQuery: Post failed: Post \"http://localhost:26657\": dial tcp 127.0.0.1:26657: connect: connection refused"}`, responseRecorder.Body.String()) - require.Equal(t, http.StatusBadRequest, responseRecorder.Code) - - // invalid request - request2 := legacyAmino.MustMarshalJSON(struct{}{}) - testRequest2, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request2)) - require.Nil(t, err) - responseRecorder = httptest.NewRecorder() - Transaction.RESTRequestHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest2) - require.Equal(t, `{"error":"failed to decode JSON payload: JSON encoding of interfaces require non-empty type field."}`, responseRecorder.Body.String()) - require.Equal(t, http.StatusBadRequest, responseRecorder.Code) - - // validate fail - request3 := legacyAmino.MustMarshalJSON(base.TransactionRequest{ - BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c"}, - ID: "ID", - }) - testRequest3, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request3)) - require.Nil(t, err) - responseRecorder = httptest.NewRecorder() - Transaction.RESTRequestHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest3) - require.Equal(t, `{"error":"chain-id required but not specified"}{"error":""}`, responseRecorder.Body.String()) - require.Equal(t, http.StatusUnauthorized, responseRecorder.Code) - - // Simulate RPC error - request4 := legacyAmino.MustMarshalJSON(base.TransactionRequest{ - BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Simulate: true}, - ID: "ID", - }) - testRequest4, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request4)) - require.Nil(t, err) - responseRecorder = httptest.NewRecorder() - Transaction.RESTRequestHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest4) - require.Equal(t, `{"error":"ABCIQuery: Post failed: Post \"http://localhost:26657\": dial tcp 127.0.0.1:26657: connect: connection refused"}`, responseRecorder.Body.String()) - require.Equal(t, http.StatusBadRequest, responseRecorder.Code) - - viper.Set(flags.FlagGenerateOnly, true) - // Generate Only - request5 := legacyAmino.MustMarshalJSON(base.TransactionRequest{ - BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test"}, - ID: "ID", - }) - testRequest5, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request5)) - require.Nil(t, err) - responseRecorder = httptest.NewRecorder() - Transaction.RESTRequestHandler(TestClientContext).ServeHTTP(responseRecorder, testRequest5) - require.Equal(t, http.StatusOK, responseRecorder.Code) - -} diff --git a/utilities/rest/queuing/kafka_test.go b/utilities/rest/queuing/kafka_test.go index cbab40a86..0141ef1a1 100644 --- a/utilities/rest/queuing/kafka_test.go +++ b/utilities/rest/queuing/kafka_test.go @@ -2,66 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package queuing - -import ( - "testing" - - codecUtilities "github.com/AssetMantle/schema/go/codec/utilities" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/utilities/random" -) - -type testMessage struct { - Name string `json:"name"` -} - -var _ sdkTypes.Msg = testMessage{} - -func (message testMessage) Route() string { return "testModule" } -func (message testMessage) Type() string { return "" } -func (message testMessage) ValidateBasic() error { - return nil -} -func (message testMessage) GetSignBytes() []byte { - return []byte{} -} -func (message testMessage) GetSigners() []sdkTypes.AccAddress { - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, _ := sdkTypes.AccAddressFromBech32(fromAddress) - return []sdkTypes.AccAddress{fromAccAddress} -} -func (testMessage) RegisterLegacyAminoCodec(legacyAmino *codec.LegacyAmino) { - codecUtilities.RegisterModuleConcrete(legacyAmino, testMessage{}) -} - -func Test_Kafka(t *testing.T) { - var legacyAmino = codec.NewLegacyAmino() - schemaCodec.RegisterLegacyAminoCodec(legacyAmino) - std.RegisterLegacyAminoCodec(legacyAmino) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test"} - ticketID := TicketID(random.GenerateUniqueIdentifier("ticket")) - kafkaPorts := []string{"localhost:9092"} - require.Panics(t, func() { - testKafkaState := NewKafkaState(kafkaPorts) - bank.RegisterCodec(legacyAmino) - message := bank.NewMsgSend(fromAccAddress, fromAccAddress, sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(123)))) - - testKafkaMsg := NewKafkaMsgFromRest(message, ticketID, testBaseReq, context) - SendToKafka(testKafkaMsg, legacyAmino) - - kafkaMsg := kafkaTopicConsumer("Topic", testKafkaState.Consumers, legacyAmino) - require.Equal(t, testKafkaMsg.TicketID, kafkaMsg.TicketID) - require.Equal(t, testKafkaMsg.BaseRequest, kafkaMsg.BaseRequest) - }) - -} diff --git a/utilities/rest/queuing/kafka_types_test.go b/utilities/rest/queuing/kafka_types_test.go index dd76f7c29..0141ef1a1 100644 --- a/utilities/rest/queuing/kafka_types_test.go +++ b/utilities/rest/queuing/kafka_types_test.go @@ -2,45 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package queuing - -import ( - "testing" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/utilities/random" -) - -func Test_Kafka_Types(t *testing.T) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - - testMessage := sdkTypes.NewTestMsg() - - ticketID := TicketID(random.GenerateUniqueIdentifier("name")) - testKafkaMsg := NewKafkaMsgFromRest(testMessage, ticketID, testBaseReq, context) - kafkaCliCtx := kafkaCliCtx{ - OutputFormat: context.OutputFormat, - ChainID: context.ChainID, - Height: context.Height, - HomeDir: context.HomeDir, - NodeURI: context.NodeURI, - From: context.From, - TrustNode: context.TrustNode, - UseLedger: context.UseLedger, - BroadcastMode: context.BroadcastMode, - Simulate: context.Simulate, - GenerateOnly: context.GenerateOnly, - FromAddress: context.FromAddress, - FromName: context.FromName, - Indent: context.Indent, - SkipConfirm: context.SkipConfirm, - } - require.Equal(t, kafkaMsg{Msg: testMessage, TicketID: ticketID, BaseRequest: testBaseReq, KafkaCliCtx: kafkaCliCtx}, testKafkaMsg) - require.Equal(t, context, cliCtxFromKafkaMsg(testKafkaMsg, context)) - // require -} diff --git a/x/classifications/queries/classification/query_request_test.go b/x/classifications/queries/classification/query_request_test.go index eaf2a3d54..29c9cadeb 100644 --- a/x/classifications/queries/classification/query_request_test.go +++ b/x/classifications/queries/classification/query_request_test.go @@ -2,218 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package classification - -import ( - "fmt" - "reflect" - "testing" - - baseData "github.com/AssetMantle/schema/go/data/base" - "github.com/AssetMantle/schema/go/ids" - baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" - "github.com/cosmos/cosmos-sdk/client" - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/helpers/constants" -) - -func createTestInput() *baseIDs.ClassificationID { - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - return classificationID.(*baseIDs.ClassificationID) -} - -func Test_newQueryRequest(t *testing.T) { - type args struct { - classificationID ids.ClassificationID - } - tests := []struct { - name string - args args - want helpers.QueryRequest - }{ - {"+ve", args{createTestInput()}, &QueryRequest{createTestInput()}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := newQueryRequest(tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { - t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequestFromInterface(t *testing.T) { - type args struct { - request helpers.QueryRequest - } - tests := []struct { - name string - args args - want helpers.QueryRequest - }{ - {"+ve", args{newQueryRequest(createTestInput())}, &QueryRequest{createTestInput()}}, - {"+ve", args{newQueryRequest(baseIDs.PrototypeClassificationID())}, &QueryRequest{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { - t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_Decode(t *testing.T) { - encodedQueryResponse, err := (&QueryRequest{createTestInput()}).Encode() - require.NoError(t, err) - encodedQueryResponse1, err := (&QueryRequest{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}).Encode() - require.NoError(t, err) - type fields struct { - ClassificationID *baseIDs.ClassificationID - } - type args struct { - bytes []byte - } - tests := []struct { - name string - fields fields - args args - want helpers.QueryRequest - wantErr bool - }{ - {"+ve", fields{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}, args{encodedQueryResponse}, &QueryRequest{createTestInput()}, false}, - {"+ve", fields{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}, args{encodedQueryResponse1}, &QueryRequest{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - ClassificationID: tt.fields.ClassificationID, - } - got, err := queryRequest.Decode(tt.args.bytes) - if (err != nil) != tt.wantErr { - t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Decode() got = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_Encode(t *testing.T) { - encodedQuery, err := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}) - require.NoError(t, err) - encodedQuery1, err := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(&QueryRequest{createTestInput()}) - require.NoError(t, err) - type fields struct { - ClassificationID *baseIDs.ClassificationID - } - tests := []struct { - name string - fields fields - want []byte - wantErr bool - }{ - {"+ve with nil", fields{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}, encodedQuery, false}, - {"+ve with nil", fields{createTestInput()}, encodedQuery1, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - ClassificationID: tt.fields.ClassificationID, - } - got, err := queryRequest.Encode() - if (err != nil) != tt.wantErr { - t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Encode() got = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_FromCLI(t *testing.T) { - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.ClassificationID}) - - type fields struct { - ClassificationID *baseIDs.ClassificationID - } - type args struct { - cliCommand helpers.CLICommand - context client.Context - } - tests := []struct { - name string - fields fields - args args - want string - wantErr bool - }{ - {"+ve", fields{}, args{cliCommand, baseHelpers.TestClientContext}, "", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - qu := &QueryRequest{ - ClassificationID: tt.fields.ClassificationID, - } - got, err := qu.FromCLI(tt.args.cliCommand, tt.args.context) - if (err != nil) != tt.wantErr { - t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(fmt.Sprint(got), tt.want) { - t.Errorf("FromCLI() got = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_Validate(t *testing.T) { - type fields struct { - ClassificationID *baseIDs.ClassificationID - } - tests := []struct { - name string - fields fields - wantErr bool - }{ - {"+ve", fields{createTestInput()}, false}, - {"+ve", fields{baseIDs.PrototypeClassificationID().(*baseIDs.ClassificationID)}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - ClassificationID: tt.fields.ClassificationID, - } - if err := queryRequest.Validate(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_requestPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.QueryRequest - }{ - {"+ve", &QueryRequest{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("requestPrototype() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/x/identities/queries/identity/query_request_test.go b/x/identities/queries/identity/query_request_test.go index 482c8eeb7..265be1823 100644 --- a/x/identities/queries/identity/query_request_test.go +++ b/x/identities/queries/identity/query_request_test.go @@ -2,240 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package identity - -import ( - "reflect" - "testing" - - baseData "github.com/AssetMantle/schema/go/data/base" - "github.com/AssetMantle/schema/go/ids" - baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" - "github.com/cosmos/cosmos-sdk/client" - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - - "github.com/AssetMantle/modules/helpers" - "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/helpers/constants" -) - -func createTestInput() (*baseIDs.IdentityID, *baseIDs.IdentityID) { - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - emptyMutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID"), baseData.NewStringData("")))) - - testClassificationID := baseIDs.NewClassificationID(immutables, mutables) - testIdentity := baseIDs.NewIdentityID(testClassificationID, immutables) - - emptyTestClassificationID := baseIDs.NewClassificationID(immutables, emptyMutables) - emptyTestIdentity := baseIDs.NewIdentityID(emptyTestClassificationID, immutables) - - return testIdentity.(*baseIDs.IdentityID), emptyTestIdentity.(*baseIDs.IdentityID) -} - -func Test_newQueryRequest(t *testing.T) { - testIdentity, emptyTestIdentity := createTestInput() - - type args struct { - identityID ids.IdentityID - } - tests := []struct { - name string - args args - want helpers.QueryRequest - }{ - - {"+ve", args{testIdentity}, &QueryRequest{testIdentity}}, - {"+ve with empty String", args{emptyTestIdentity}, &QueryRequest{emptyTestIdentity}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := newQueryRequest(tt.args.identityID); !reflect.DeepEqual(got, tt.want) { - t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequestFromInterface(t *testing.T) { - testIdentity, emptyTestIdentity := createTestInput() - type args struct { - request helpers.QueryRequest - } - tests := []struct { - name string - args args - want helpers.QueryRequest - }{ - - {"+ve", args{newQueryRequest(testIdentity)}, &QueryRequest{testIdentity}}, - {"+ve with empty string", args{newQueryRequest(emptyTestIdentity)}, &QueryRequest{emptyTestIdentity}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { - t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_Decode(t *testing.T) { - testIdentity, emptyTestIdentity := createTestInput() - testQueryRequest := newQueryRequest(testIdentity) - encodedRequest, err := testQueryRequest.Encode() - require.Nil(t, err) - randomDecode, _ := (&QueryRequest{emptyTestIdentity}).Encode() - type fields struct { - IdentityID *baseIDs.IdentityID - } - type args struct { - bytes []byte - } - tests := []struct { - name string - fields fields - args args - want helpers.QueryRequest - wantErr bool - }{ - - {"+ve", fields{testIdentity}, args{encodedRequest}, testQueryRequest, false}, - {"+ve", fields{emptyTestIdentity}, args{randomDecode}, &QueryRequest{emptyTestIdentity}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - IdentityID: tt.fields.IdentityID, - } - got, err := queryRequest.Decode(tt.args.bytes) - if (err != nil) != tt.wantErr { - t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Decode() got = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_Encode(t *testing.T) { - testIdentity, emptyTestIdentity := createTestInput() - byteArr, _ := base.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(testIdentity)) - byteArr2, _ := base.CodecPrototype().GetLegacyAmino().MarshalJSON(newQueryRequest(emptyTestIdentity)) - - type fields struct { - IdentityID *baseIDs.IdentityID - } - tests := []struct { - name string - fields fields - want []byte - wantErr bool - }{ - - {"+ve", fields{testIdentity}, byteArr, false}, - {"+ve with empty String ID", fields{emptyTestIdentity}, byteArr2, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - IdentityID: tt.fields.IdentityID, - } - got, err := queryRequest.Encode() - if (err != nil) != tt.wantErr { - t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Encode() got = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_queryRequest_FromCLI(t *testing.T) { - testIdentity, _ := createTestInput() - cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.IdentityID}) - - viper.Set(constants.IdentityID.GetName(), testIdentity.String()) - type fields struct { - IdentityID *baseIDs.IdentityID - } - type args struct { - cliCommand helpers.CLICommand - context client.Context - } - tests := []struct { - name string - fields fields - args args - want helpers.QueryRequest - wantErr bool - }{ - {"+ve", fields{testIdentity}, args{cliCommand, base.TestClientContext}, newQueryRequest(testIdentity), false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - IdentityID: tt.fields.IdentityID, - } - if got, err := queryRequest.FromCLI(tt.args.cliCommand, tt.args.context); !reflect.DeepEqual(got, tt.want) { - if (err != nil) != tt.wantErr { - t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("FromCLI() got = %v, want %v", got, tt.want) - } - } - }) - } -} - -func Test_queryRequest_Validate(t *testing.T) { - testIdentity, emptyTestIdentity := createTestInput() - type fields struct { - IdentityID *baseIDs.IdentityID - } - tests := []struct { - name string - fields fields - wantErr bool - }{ - - {"+ve", fields{testIdentity}, false}, - {"+ve with empty IdentityID", fields{emptyTestIdentity}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - queryRequest := &QueryRequest{ - IdentityID: tt.fields.IdentityID, - } - if err := queryRequest.Validate(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - -func Test_requestPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.QueryRequest - }{ - - {"+ve", &QueryRequest{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("requestPrototype() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/x/splits/queries/balances/query_response_test.go b/x/splits/queries/balances/query_response_test.go index aa24fddf2..41f53a02d 100644 --- a/x/splits/queries/balances/query_response_test.go +++ b/x/splits/queries/balances/query_response_test.go @@ -2,29 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package balances - -import ( - "testing" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - baseHelpers "github.com/AssetMantle/modules/helpers/base" -) - -func Test_Split_Response(t *testing.T) { - - testQueryResponse := newQueryResponse(sdkTypes.OneInt()) - - encodedResponse, _ := testQueryResponse.Encode() - bytes, _ := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(testQueryResponse) - require.Equal(t, bytes, encodedResponse) - - decodedResponse, _ := (&QueryResponse{}).Decode(bytes) - require.Equal(t, testQueryResponse, decodedResponse) - - decodedResponse2, _ := (&QueryResponse{}).Decode([]byte{}) - require.Equal(t, nil, decodedResponse2) - - require.Equal(t, &QueryResponse{}, responsePrototype()) -} diff --git a/x/splits/queries/split/query_response_test.go b/x/splits/queries/split/query_response_test.go index 33e676328..74c57b56e 100644 --- a/x/splits/queries/split/query_response_test.go +++ b/x/splits/queries/split/query_response_test.go @@ -2,57 +2,3 @@ // SPDX-License-Identifier: Apache-2.0 package split - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" - tendermintDB "github.com/tendermint/tm-db" - - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/splits/mapper" -) - -func CreateTestInput(t *testing.T) sdkTypes.Context { - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - return context -} - -func Test_Split_Response(t *testing.T) { - context := CreateTestInput(t) - collection := mapper.Prototype().NewCollection(sdkTypes.WrapSDKContext(context)) - - testQueryResponse := newQueryResponse(collection) - - encodedResponse, _ := testQueryResponse.Encode() - bytes, _ := baseHelpers.CodecPrototype().GetLegacyAmino().MarshalJSON(testQueryResponse) - require.Equal(t, bytes, encodedResponse) - - decodedResponse, _ := (&QueryResponse{}).Decode(bytes) - require.Equal(t, testQueryResponse, decodedResponse) - - decodedResponse2, _ := (&QueryResponse{}).Decode([]byte{}) - require.Equal(t, nil, decodedResponse2) - - require.Equal(t, &QueryResponse{}, responsePrototype()) -} From c5317e4e771b16b2ec4deeb49d9800fe288a5b15 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 8 Mar 2024 18:29:02 +0530 Subject: [PATCH 03/57] feat(utilities):Add GenerateUniqueIdentifierList function in id.go This commit adds a new function GenerateUniqueIdentifierList in the utilities module. The function generates a list of unique IDs with a given prefix and count, which can be used for testing and client utility purposes. --- utilities/random/id.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/utilities/random/id.go b/utilities/random/id.go index c5ae3f84f..a7f34f8c3 100644 --- a/utilities/random/id.go +++ b/utilities/random/id.go @@ -30,3 +30,38 @@ func GenerateUniqueIdentifier(prefix ...string) string { strconv.Itoa(10000000+int(time.Now().UnixNano())%89999999) + strconv.FormatInt(10000+randomNumber.Int64(), 10) } + +// GenerateUniqueIdentifierList generates a list of unique IDs with the given prefix and count. +// The returned value is a slice of strings. +// The prefix is used to customize the generated IDs. +// The count specifies the number of IDs to generate. +// Each generated ID is unique. +// +// Example: +// ids := GenerateUniqueIdentifierList("user-", 5) +// +// The above example will generate 5 unique IDs with the prefix "user-". +// The returned slice will contain ["user-123...1", "user-234...2", "user-345...3", "user-456...4", "user-567...5"]. +// +// Warning: This function is non-deterministic and is not suitable for generating blockchain state. +// It is intended for testing and client utility purposes only. +// +// Dependencies: +// The function depends on the GenerateUniqueIdentifier function. +// +// Code Snippet: +// +// func GenerateUniqueIdentifierList(prefix string, count int) []string { +// ids := make([]string, count) +// for i := 0; i < count; i++ { +// ids[i] = GenerateUniqueIdentifier(prefix) +// } +// return ids +// } +func GenerateUniqueIdentifierList(prefix string, count int) []string { + ids := make([]string, count) + for i := 0; i < count; i++ { + ids[i] = GenerateUniqueIdentifier(prefix) + } + return ids +} From 781063686dd934e1ba9ef26c1b32264f54a0f377 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 8 Mar 2024 18:32:35 +0530 Subject: [PATCH 04/57] feat(helpers):adding collection codec and auxiliary tests --- helpers/base/auxiliaries_test.go | 175 +++++++++++++++++++++++++++++++ helpers/base/codec_test.go | 87 +++++++++++++++ helpers/base/collection_test.go | 160 ++++++++++++++++++++++++++++ 3 files changed, 422 insertions(+) create mode 100644 helpers/base/auxiliaries_test.go create mode 100644 helpers/base/codec_test.go diff --git a/helpers/base/auxiliaries_test.go b/helpers/base/auxiliaries_test.go new file mode 100644 index 000000000..3c56a65e1 --- /dev/null +++ b/helpers/base/auxiliaries_test.go @@ -0,0 +1,175 @@ +package base + +import ( + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/stretchr/testify/assert" + "testing" +) + +var ( + randomUniqueIdentifiers = random.GenerateUniqueIdentifierList("", 2) +) + +type mockAuxiliary struct { + name string +} + +func (m mockAuxiliary) GetName() string { + return m.name +} + +func (m mockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + // Stubbed return as it is not used in GetAuxiliary + return nil +} + +func (m mockAuxiliary) Initialize(helpers.Mapper, helpers.ParameterManager, ...interface{}) helpers.Auxiliary { + // Stubbed return as it is not used in GetAuxiliary + return nil +} + +func TestGetAuxiliary(t *testing.T) { + tests := []struct { + name string + auxiliaries auxiliaries + arg string + want helpers.Auxiliary + }{ + { + name: "Empty AuxiliaryList", + auxiliaries: auxiliaries{}, + arg: "auxiliary1", + want: nil, + }, + { + name: "Nil Return Non-Existing Name", + auxiliaries: auxiliaries{auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}}, + arg: "nonexistent", + want: nil, + }, + { + name: "Flyweight1", + auxiliaries: auxiliaries{auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}}, + arg: randomUniqueIdentifiers[0], + want: mockAuxiliary{randomUniqueIdentifiers[0]}, + }, + { + name: "Flyweight2", + auxiliaries: auxiliaries{auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}}, + arg: randomUniqueIdentifiers[1], + want: mockAuxiliary{randomUniqueIdentifiers[1]}, + }, + { + name: "Unordered Flyweight1", + auxiliaries: auxiliaries{auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[1]}, mockAuxiliary{randomUniqueIdentifiers[0]}}}, + arg: randomUniqueIdentifiers[0], + want: mockAuxiliary{randomUniqueIdentifiers[0]}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.auxiliaries.GetAuxiliary(tt.arg); got != tt.want { + t.Errorf("GetAuxiliary() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaries_Get(t *testing.T) { + type fields struct { + auxiliaryList []helpers.Auxiliary + } + tests := []struct { + name string + fields fields + want []helpers.Auxiliary + }{ + { + name: "Empty AuxiliaryList", + fields: fields{ + auxiliaryList: []helpers.Auxiliary{}, + }, + want: []helpers.Auxiliary{}, + }, + { + name: "Non-empty AuxiliaryList", + fields: fields{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + want: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + { + name: "Nil Auxiliary", + fields: fields{ + auxiliaryList: []helpers.Auxiliary{nil}, + }, + want: []helpers.Auxiliary{nil}, + }, + { + name: "Nil Auxiliary in list", + fields: fields{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, nil, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + want: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, nil, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaries := auxiliaries{ + auxiliaryList: tt.fields.auxiliaryList, + } + assert.Equalf(t, tt.want, auxiliaries.Get(), "Get()") + }) + } +} + +func TestNewAuxiliaries(t *testing.T) { + type args struct { + auxiliaryList []helpers.Auxiliary + } + tests := []struct { + name string + args args + want helpers.Auxiliaries + }{ + { + name: "Empty AuxiliaryList", + args: args{ + auxiliaryList: []helpers.Auxiliary{}, + }, + want: auxiliaries{ + auxiliaryList: []helpers.Auxiliary{}, + }, + }, + { + name: "Non-empty AuxiliaryList", + args: args{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + want: auxiliaries{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + }, + { + name: "Nil Auxiliary", + args: args{ + auxiliaryList: []helpers.Auxiliary{nil}, + }, + want: auxiliaries{ + auxiliaryList: []helpers.Auxiliary{nil}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxListInterface := make([]interface{}, len(tt.args.auxiliaryList)) + for i, v := range tt.args.auxiliaryList { + auxListInterface[i] = v + } + assert.Equalf(t, tt.want, NewAuxiliaries(tt.args.auxiliaryList...), "NewAuxiliaries(%v)", auxListInterface...) + }) + } +} diff --git a/helpers/base/codec_test.go b/helpers/base/codec_test.go new file mode 100644 index 000000000..850288ddb --- /dev/null +++ b/helpers/base/codec_test.go @@ -0,0 +1,87 @@ +package base + +import ( + "github.com/AssetMantle/modules/helpers" + "github.com/cosmos/cosmos-sdk/client" + sdkCodec "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + sdkModuleTypes "github.com/cosmos/cosmos-sdk/types/module" + "github.com/stretchr/testify/assert" + "testing" +) + +type mockTxConfig struct { + client.TxConfig +} + +func Test_codec_Initialize(t *testing.T) { + type fields struct { + interfaceRegistry types.InterfaceRegistry + TxConfig client.TxConfig + legacyAmino *sdkCodec.LegacyAmino + ProtoCodec *sdkCodec.ProtoCodec + } + type args struct { + moduleBasicManager sdkModuleTypes.BasicManager + } + tests := []struct { + name string + fields fields + args args + want helpers.Codec + }{ + { + name: "Test codec Initialize", + fields: fields{ + interfaceRegistry: types.NewInterfaceRegistry(), + TxConfig: mockTxConfig{}, + legacyAmino: sdkCodec.NewLegacyAmino(), + ProtoCodec: sdkCodec.NewProtoCodec(types.NewInterfaceRegistry()), + }, + args: args{ + moduleBasicManager: sdkModuleTypes.BasicManager{}, + }, + want: codec{ + interfaceRegistry: types.NewInterfaceRegistry(), + TxConfig: mockTxConfig{}, + legacyAmino: sdkCodec.NewLegacyAmino(), + ProtoCodec: sdkCodec.NewProtoCodec(types.NewInterfaceRegistry()), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + codec := codec{ + interfaceRegistry: tt.fields.interfaceRegistry, + TxConfig: tt.fields.TxConfig, + legacyAmino: tt.fields.legacyAmino, + ProtoCodec: tt.fields.ProtoCodec, + } + Codec := codec.Initialize(tt.args.moduleBasicManager) + assert.Equalf(t, tt.want.GetProtoCodec(), Codec.GetProtoCodec(), "Initialize(%v)", tt.args.moduleBasicManager) + }) + } +} + +func TestCodecPrototype(t *testing.T) { + tests := []struct { + name string + expectedInterface helpers.Codec + }{ + { + name: "codec prototype", + expectedInterface: CodecPrototype(), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := CodecPrototype() + assert.IsType(t, test.expectedInterface, got) + assert.NotNil(t, got.GetProtoCodec()) + assert.NotNil(t, got.GetLegacyAmino()) + assert.NotNil(t, got.InterfaceRegistry()) + }) + } +} diff --git a/helpers/base/collection_test.go b/helpers/base/collection_test.go index 1944e7a61..ffe361a57 100644 --- a/helpers/base/collection_test.go +++ b/helpers/base/collection_test.go @@ -2,3 +2,163 @@ // SPDX-License-Identifier: Apache-2.0 package base + +import ( + "context" + "github.com/AssetMantle/modules/helpers" + "github.com/cosmos/cosmos-sdk/store/types" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/kv" + "github.com/stretchr/testify/assert" + "testing" +) + +type MockRecord struct { + key helpers.Key +} + +func (mr MockRecord) GetKey() helpers.Key { + return mr.key +} + +func (mr MockRecord) GetMappable() helpers.Mappable { + return nil +} + +func (mr MockRecord) WithKey(helpers.Key) helpers.Record { + return nil +} + +func (mr MockRecord) ReadFromIterator(sdkTypes.Iterator) helpers.Record { + return nil +} + +func (mr MockRecord) Read(types.KVStore) helpers.Record { + return nil +} + +func (mr MockRecord) Write(types.KVStore) helpers.Record { + return nil +} + +func (mr MockRecord) Delete(types.KVStore) { +} + +type MockMapper struct { +} + +func (mm MockMapper) NewCollection(_ context.Context) helpers.Collection { + return nil +} + +func (mm MockMapper) StoreDecoder(_ kv.Pair, _ kv.Pair) string { + return "" +} + +func (mm MockMapper) Initialize(_ *sdkTypes.KVStoreKey) helpers.Mapper { + return nil +} + +func (mm MockMapper) Read(context.Context, helpers.Key) helpers.Record { + return nil +} + +func (mm MockMapper) Upsert(context.Context, helpers.Record) { +} + +func (mm MockMapper) IterateAll(context.Context, func(helpers.Record) bool) { +} + +func (mm MockMapper) FetchAll(context.Context) []helpers.Record { + return nil +} + +func (mm MockMapper) Delete(context.Context, helpers.Key) { +} + +func (mm MockMapper) Iterate(context.Context, helpers.Key, func(helpers.Record) bool) { +} + +func (mm MockMapper) IteratePaginated(context.Context, helpers.Key, int32, func(helpers.Record) bool) { +} + +func TestMutate(t *testing.T) { + tt := []struct { + name string + mapper helpers.Mapper + input helpers.Record + expected helpers.Collection + }{ + { + name: "Empty records", + mapper: MockMapper{}, + input: MockRecord{}, + expected: collection{records: []helpers.Record{}, mapper: MockMapper{}, context: nil}, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + c := collection{ + records: []helpers.Record{}, + mapper: tc.mapper, + context: nil, + } + + output := c.Mutate(tc.input) + + for i := range output.Get() { + if output.Get()[i].GetKey() != tc.expected.Get()[i].GetKey() { + t.Errorf("Record key not match. Got %v, wants %v", output.Get()[i].GetKey(), tc.expected.Get()[i].GetKey()) + } + } + }) + } +} + +func Test_collection_Initialize(t *testing.T) { + type fields struct { + records []helpers.Record + mapper helpers.Mapper + context context.Context + } + type args struct { + context context.Context + mapper helpers.Mapper + } + tests := []struct { + name string + fields fields + args args + want helpers.Collection + }{ + { + name: "Test collection Initialize", + fields: fields{ + records: []helpers.Record{}, + mapper: nil, + context: context.Background(), + }, + args: args{ + context: context.Background(), + mapper: nil, + }, + want: collection{ + records: []helpers.Record{}, + mapper: nil, + context: context.Background(), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + collection := collection{ + records: tt.fields.records, + mapper: tt.fields.mapper, + context: tt.fields.context, + } + assert.Equalf(t, tt.want, collection.Initialize(tt.args.context, tt.args.mapper), "Initialize(%v, %v)", tt.args.context, tt.args.mapper) + }) + } +} From fd2a0ea6fd26f51869e13c63eb537a5b47637ad0 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 13 Mar 2024 15:26:26 +0530 Subject: [PATCH 05/57] feat(helpers):adding invariants test --- helpers/base/invariants_test.go | 82 +++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 helpers/base/invariants_test.go diff --git a/helpers/base/invariants_test.go b/helpers/base/invariants_test.go new file mode 100644 index 000000000..1375af7f2 --- /dev/null +++ b/helpers/base/invariants_test.go @@ -0,0 +1,82 @@ +package base + +import ( + "github.com/AssetMantle/modules/helpers" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestNewInvariants(t *testing.T) { + type args struct { + moduleName string + route string + invariantList []sdkTypes.Invariant + } + tests := []struct { + name string + args args + want helpers.Invariants + }{ + { + name: "Test NewInvariants", + args: args{ + moduleName: "test", + route: "test", + invariantList: []sdkTypes.Invariant{}, + }, + want: invariants{ + moduleName: "test", + route: "test", + invariantList: []sdkTypes.Invariant{}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var interfaceList []interface{} + for _, invariant := range tt.args.invariantList { + interfaceList = append(interfaceList, invariant) + } + assert.Equalf(t, tt.want, NewInvariants(tt.args.moduleName, tt.args.route, tt.args.invariantList...), "NewInvariants(%v, %v, %v)", tt.args.moduleName, tt.args.route, interfaceList) + }) + } +} + +func Test_invariants_Register(t *testing.T) { + type fields struct { + moduleName string + route string + invariantList []sdkTypes.Invariant + } + type args struct { + invariantRegistry sdkTypes.InvariantRegistry + } + tests := []struct { + name string + fields fields + args args + }{ + { + name: "Test invariants Register", + fields: fields{ + moduleName: "test", + route: "test", + invariantList: []sdkTypes.Invariant{}, + }, + args: args{ + invariantRegistry: nil, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + invariants := invariants{ + moduleName: tt.fields.moduleName, + route: tt.fields.route, + invariantList: tt.fields.invariantList, + } + invariants.Register(tt.args.invariantRegistry) + }) + } +} From ec288ddd3dc5c43d07dd43d915c31270cf014790 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 13 Mar 2024 23:19:08 +0530 Subject: [PATCH 06/57] refactor(test_constants): retiring usage of TestClientContext --- helpers/base/test_constants.go | 7 ------- x/assets/queries/asset/query_request_test.go | 2 +- x/assets/transactions/burn/transaction_request_test.go | 2 +- x/assets/transactions/define/transaction_request_test.go | 2 +- x/assets/transactions/deputize/transaction_request_test.go | 2 +- x/assets/transactions/mint/transaction_request_test.go | 2 +- x/assets/transactions/mutate/transaction_request_test.go | 2 +- .../transactions/renumerate/transaction_request_test.go | 2 +- x/assets/transactions/revoke/transaction_request_test.go | 2 +- x/assets/transactions/send/transaction_request_test.go | 2 +- x/assets/transactions/unwrap/transaction_request_test.go | 2 +- x/assets/transactions/wrap/transaction_request_test.go | 2 +- .../transactions/define/transaction_request_test.go | 2 +- .../transactions/deputize/transaction_request_test.go | 6 +++--- .../transactions/issue/transaction_request_test.go | 4 ++-- x/identities/transactions/name/transaction_request_test.go | 4 ++-- .../transactions/provision/transaction_request_test.go | 2 +- .../transactions/quash/transaction_request_test.go | 2 +- .../transactions/revoke/transaction_request_test.go | 2 +- .../transactions/unprovision/transaction_request_test.go | 2 +- .../transactions/update/transaction_request_test.go | 2 +- x/metas/transactions/reveal/transaction_request_test.go | 5 +++-- x/orders/queries/order/query_request_test.go | 2 +- x/orders/transactions/cancel/transaction_request_test.go | 2 +- x/orders/transactions/define/transaction_request_test.go | 2 +- x/orders/transactions/deputize/transaction_request_test.go | 2 +- x/orders/transactions/get/transaction_request_test.go | 2 +- .../transactions/immediate/transaction_request_test.go | 2 +- x/orders/transactions/make/transaction_request_test.go | 2 +- x/orders/transactions/modify/transaction_request_test.go | 2 +- x/orders/transactions/put/transaction_request_test.go | 2 +- x/orders/transactions/revoke/transaction_request_test.go | 2 +- x/orders/transactions/take/transaction_request_test.go | 2 +- x/splits/queries/balances/query_request_test.go | 2 +- x/splits/queries/split/query_request_test.go | 2 +- x/splits/queries/supply/query_request_test.go | 2 +- 36 files changed, 41 insertions(+), 47 deletions(-) delete mode 100644 helpers/base/test_constants.go diff --git a/helpers/base/test_constants.go b/helpers/base/test_constants.go deleted file mode 100644 index 1241bef5a..000000000 --- a/helpers/base/test_constants.go +++ /dev/null @@ -1,7 +0,0 @@ -package base - -import ( - "github.com/cosmos/cosmos-sdk/client" -) - -var TestClientContext = client.Context{}.WithCodec(CodecPrototype()) diff --git a/x/assets/queries/asset/query_request_test.go b/x/assets/queries/asset/query_request_test.go index dfabcaba8..0aca6fa1b 100644 --- a/x/assets/queries/asset/query_request_test.go +++ b/x/assets/queries/asset/query_request_test.go @@ -160,7 +160,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testKey}, args{cliCommand, base.TestClientContext}, newQueryRequest(testAssetID), false}, + {"+ve", fields{testKey}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newQueryRequest(testAssetID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/burn/transaction_request_test.go b/x/assets/transactions/burn/transaction_request_test.go index 955881c8f..4fdc20da3 100644 --- a/x/assets/transactions/burn/transaction_request_test.go +++ b/x/assets/transactions/burn/transaction_request_test.go @@ -84,7 +84,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{BaseReq: testBaseRequest, FromID: fromID.AsString(), AssetID: testAssetID.AsString()}, args{cliCommand, base.TestClientContext}, newTransactionRequest(testBaseRequest, fromID.AsString(), testAssetID.AsString()), false}, + {"+ve", fields{BaseReq: testBaseRequest, FromID: fromID.AsString(), AssetID: testAssetID.AsString()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newTransactionRequest(testBaseRequest, fromID.AsString(), testAssetID.AsString()), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/define/transaction_request_test.go b/x/assets/transactions/define/transaction_request_test.go index f95152d59..f0b3b79df 100644 --- a/x/assets/transactions/define/transaction_request_test.go +++ b/x/assets/transactions/define/transaction_request_test.go @@ -104,7 +104,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/deputize/transaction_request_test.go b/x/assets/transactions/deputize/transaction_request_test.go index bc155fee6..a827660ac 100644 --- a/x/assets/transactions/deputize/transaction_request_test.go +++ b/x/assets/transactions/deputize/transaction_request_test.go @@ -113,7 +113,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString(), mutableMetaPropertiesString, true, true, true, true, true, true}, false}, + {"+ve", fields{}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString(), mutableMetaPropertiesString, true, true, true, true, true, true}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/mint/transaction_request_test.go b/x/assets/transactions/mint/transaction_request_test.go index cb1b344d4..394b42d03 100644 --- a/x/assets/transactions/mint/transaction_request_test.go +++ b/x/assets/transactions/mint/transaction_request_test.go @@ -110,7 +110,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/mutate/transaction_request_test.go b/x/assets/transactions/mutate/transaction_request_test.go index c196a1d4a..cf25e62cd 100644 --- a/x/assets/transactions/mutate/transaction_request_test.go +++ b/x/assets/transactions/mutate/transaction_request_test.go @@ -97,7 +97,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), testAssetID.AsString(), mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), testAssetID.AsString(), mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), testAssetID.AsString(), mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), testAssetID.AsString(), mutableMetaPropertiesString, mutablePropertiesString}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/renumerate/transaction_request_test.go b/x/assets/transactions/renumerate/transaction_request_test.go index 8cf032fab..9e0db06bd 100644 --- a/x/assets/transactions/renumerate/transaction_request_test.go +++ b/x/assets/transactions/renumerate/transaction_request_test.go @@ -83,7 +83,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), testAssetID.AsString()}, args{cliCommand, base.TestClientContext}, newTransactionRequest(testBaseRequest, fromID.AsString(), testAssetID.AsString()), false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), testAssetID.AsString()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newTransactionRequest(testBaseRequest, fromID.AsString(), testAssetID.AsString()), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/revoke/transaction_request_test.go b/x/assets/transactions/revoke/transaction_request_test.go index 06393d644..95678625e 100644 --- a/x/assets/transactions/revoke/transaction_request_test.go +++ b/x/assets/transactions/revoke/transaction_request_test.go @@ -86,7 +86,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString()}, args{cliCommand, base.TestClientContext}, newTransactionRequest(testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString()), false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newTransactionRequest(testBaseRequest, fromID.AsString(), fromID.AsString(), classificationID.AsString()), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/send/transaction_request_test.go b/x/assets/transactions/send/transaction_request_test.go index c0ed2fbb3..4cd72a48b 100644 --- a/x/assets/transactions/send/transaction_request_test.go +++ b/x/assets/transactions/send/transaction_request_test.go @@ -104,7 +104,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), fromID.AsString(), assetID.AsString(), testRate.String()}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), assetID.AsString(), testRate.String()}, false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), fromID.AsString(), assetID.AsString(), testRate.String()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), fromID.AsString(), assetID.AsString(), testRate.String()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/unwrap/transaction_request_test.go b/x/assets/transactions/unwrap/transaction_request_test.go index e90921dcd..6fa7223fc 100644 --- a/x/assets/transactions/unwrap/transaction_request_test.go +++ b/x/assets/transactions/unwrap/transaction_request_test.go @@ -100,7 +100,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), coins.String()}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), coins.String()}, false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), coins.String()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), coins.String()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/assets/transactions/wrap/transaction_request_test.go b/x/assets/transactions/wrap/transaction_request_test.go index bd307d28c..89a674875 100644 --- a/x/assets/transactions/wrap/transaction_request_test.go +++ b/x/assets/transactions/wrap/transaction_request_test.go @@ -96,7 +96,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, fromID.AsString(), coins.String()}, args{cliCommand, base.TestClientContext}, transactionRequest{testBaseRequest, fromID.AsString(), coins.String()}, false}, + {"+ve", fields{testBaseRequest, fromID.AsString(), coins.String()}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, transactionRequest{testBaseRequest, fromID.AsString(), coins.String()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/define/transaction_request_test.go b/x/identities/transactions/define/transaction_request_test.go index a0b7d1f16..fd99eabea 100644 --- a/x/identities/transactions/define/transaction_request_test.go +++ b/x/identities/transactions/define/transaction_request_test.go @@ -98,7 +98,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { wantErr bool }{ - {"+ve", fields{BaseReq: testBaseReq, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(baseHelpers.TestClientContext), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, + {"+ve", fields{BaseReq: testBaseReq, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(client.Context{}.WithCodec(baseHelpers.CodecPrototype())), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/deputize/transaction_request_test.go b/x/identities/transactions/deputize/transaction_request_test.go index 0b509f29f..f5ce2c58a 100644 --- a/x/identities/transactions/deputize/transaction_request_test.go +++ b/x/identities/transactions/deputize/transaction_request_test.go @@ -94,9 +94,9 @@ func Test_transactionRequest_FromCLI(t *testing.T) { wantErr bool }{ {"+ve", - fields{BaseReq: rest.BaseReq{From: baseHelpers.TestClientContext.GetFromAddress().String(), ChainID: baseHelpers.TestClientContext.ChainID, Simulate: baseHelpers.TestClientContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanIssueIdentity: false, CanQuashIdentity: false, CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, - args{cliCommand, baseHelpers.TestClientContext}, - transactionRequest{BaseReq: rest.BaseReq{From: baseHelpers.TestClientContext.GetFromAddress().String(), ChainID: baseHelpers.TestClientContext.ChainID, Simulate: baseHelpers.TestClientContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanIssueIdentity: false, CanQuashIdentity: false, CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, + fields{BaseReq: rest.BaseReq{From: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).GetFromAddress().String(), ChainID: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).ChainID, Simulate: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanIssueIdentity: false, CanQuashIdentity: false, CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, + args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, + transactionRequest{BaseReq: rest.BaseReq{From: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).GetFromAddress().String(), ChainID: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).ChainID, Simulate: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanIssueIdentity: false, CanQuashIdentity: false, CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, false}} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/issue/transaction_request_test.go b/x/identities/transactions/issue/transaction_request_test.go index 5164d99ce..7818a5c08 100644 --- a/x/identities/transactions/issue/transaction_request_test.go +++ b/x/identities/transactions/issue/transaction_request_test.go @@ -62,7 +62,7 @@ func createTestInputForRequest(t *testing.T) (*codec.LegacyAmino, helpers.CLICom testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - return legacyAmino, cliCommand, baseHelpers.TestClientContext, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, toAddress, toAccAddress, testBaseReq + return legacyAmino, cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype()), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, toAddress, toAccAddress, testBaseReq } func Test_newTransactionRequest(t *testing.T) { @@ -134,7 +134,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(context), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ClassificationID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(context), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ClassificationID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/name/transaction_request_test.go b/x/identities/transactions/name/transaction_request_test.go index 890a2326e..1625633b1 100644 --- a/x/identities/transactions/name/transaction_request_test.go +++ b/x/identities/transactions/name/transaction_request_test.go @@ -31,7 +31,7 @@ func CreateTestInputForRequest(t *testing.T) (*codec.LegacyAmino, helpers.CLICom testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - return legacyAmino, cliCommand, baseHelpers.TestClientContext, fromAddress, fromAccAddress, testBaseReq + return legacyAmino, cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype()), fromAddress, fromAccAddress, testBaseReq } func Test_newTransactionRequest(t *testing.T) { @@ -90,7 +90,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, "nubID"}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(context), cliCommand.ReadString(constants.Name)}, false}, + {"+ve", fields{testBaseReq, "nubID"}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(context), cliCommand.ReadString(constants.Name)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/provision/transaction_request_test.go b/x/identities/transactions/provision/transaction_request_test.go index faf258242..1c7e0ffa3 100644 --- a/x/identities/transactions/provision/transaction_request_test.go +++ b/x/identities/transactions/provision/transaction_request_test.go @@ -95,7 +95,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, testToAddress, testFromID.AsString()}, args{cliCommand: cliCommand, context: baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(baseHelpers.TestClientContext), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, + {"+ve", fields{testBaseReq, testToAddress, testFromID.AsString()}, args{cliCommand: cliCommand, context: client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(client.Context{}.WithCodec(baseHelpers.CodecPrototype())), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/quash/transaction_request_test.go b/x/identities/transactions/quash/transaction_request_test.go index 001115251..d3cb26d6b 100644 --- a/x/identities/transactions/quash/transaction_request_test.go +++ b/x/identities/transactions/quash/transaction_request_test.go @@ -95,7 +95,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, testFromID.AsString(), testFromID.AsString()}, args{cliCommand: cliCommand, context: baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(baseHelpers.TestClientContext), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.IdentityID)}, false}, + {"+ve", fields{testBaseReq, testFromID.AsString(), testFromID.AsString()}, args{cliCommand: cliCommand, context: client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(client.Context{}.WithCodec(baseHelpers.CodecPrototype())), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.IdentityID)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/revoke/transaction_request_test.go b/x/identities/transactions/revoke/transaction_request_test.go index dfe58542f..3513dddc7 100644 --- a/x/identities/transactions/revoke/transaction_request_test.go +++ b/x/identities/transactions/revoke/transaction_request_test.go @@ -99,7 +99,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, testFromID.AsString(), testToID.AsString(), testClassificationID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(baseHelpers.TestClientContext), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ToIdentityID), cliCommand.ReadString(constants.ClassificationID)}, false}, + {"+ve", fields{testBaseReq, testFromID.AsString(), testToID.AsString(), testClassificationID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(client.Context{}.WithCodec(baseHelpers.CodecPrototype())), cliCommand.ReadString(constants.FromIdentityID), cliCommand.ReadString(constants.ToIdentityID), cliCommand.ReadString(constants.ClassificationID)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/unprovision/transaction_request_test.go b/x/identities/transactions/unprovision/transaction_request_test.go index 459885c63..afee80104 100644 --- a/x/identities/transactions/unprovision/transaction_request_test.go +++ b/x/identities/transactions/unprovision/transaction_request_test.go @@ -105,7 +105,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseReq, toAddress, testIdentityID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{cliCommand.ReadBaseReq(baseHelpers.TestClientContext), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, + {"+ve", fields{testBaseReq, toAddress, testIdentityID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{cliCommand.ReadBaseReq(client.Context{}.WithCodec(baseHelpers.CodecPrototype())), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/identities/transactions/update/transaction_request_test.go b/x/identities/transactions/update/transaction_request_test.go index a023b4d2d..83a75b96a 100644 --- a/x/identities/transactions/update/transaction_request_test.go +++ b/x/identities/transactions/update/transaction_request_test.go @@ -43,7 +43,7 @@ func createTestInput(t *testing.T) (*codec.LegacyAmino, helpers.CLICommand, clie testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - return legacyAmino, cliCommand, baseHelpers.TestClientContext, mutableMetaPropertiesString, mutablePropertiesString, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, testBaseReq + return legacyAmino, cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype()), mutableMetaPropertiesString, mutablePropertiesString, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, testBaseReq } func Test_newTransactionRequest(t *testing.T) { diff --git a/x/metas/transactions/reveal/transaction_request_test.go b/x/metas/transactions/reveal/transaction_request_test.go index a8459249f..df7b1848e 100644 --- a/x/metas/transactions/reveal/transaction_request_test.go +++ b/x/metas/transactions/reveal/transaction_request_test.go @@ -5,6 +5,7 @@ package reveal import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/client" "testing" "github.com/cosmos/cosmos-sdk/codec" @@ -28,9 +29,9 @@ func Test_Reveal_Request(t *testing.T) { require.Equal(t, transactionRequest{BaseReq: testBaseReq, Data: data}, testTransactionRequest) require.Equal(t, nil, testTransactionRequest.Validate()) - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, baseHelpers.TestClientContext) + requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())) require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: baseHelpers.TestClientContext.GetFromAddress().String(), ChainID: baseHelpers.TestClientContext.ChainID, Simulate: baseHelpers.TestClientContext.Simulate}, Data: ""}, requestFromCLI) + require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).GetFromAddress().String(), ChainID: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).ChainID, Simulate: client.Context{}.WithCodec(baseHelpers.CodecPrototype()).Simulate}, Data: ""}, requestFromCLI) jsonMessage, _ := json.Marshal(testTransactionRequest) transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) diff --git a/x/orders/queries/order/query_request_test.go b/x/orders/queries/order/query_request_test.go index 86cebd493..e5a692839 100644 --- a/x/orders/queries/order/query_request_test.go +++ b/x/orders/queries/order/query_request_test.go @@ -165,7 +165,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testKey}, args{cliCommand, baseHelpers.TestClientContext}, newQueryRequest(testOrderID), false}, + {"+ve", fields{testKey}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newQueryRequest(testOrderID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/cancel/transaction_request_test.go b/x/orders/transactions/cancel/transaction_request_test.go index e4e955abe..80382f0a7 100644 --- a/x/orders/transactions/cancel/transaction_request_test.go +++ b/x/orders/transactions/cancel/transaction_request_test.go @@ -99,7 +99,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testOrderID.AsString()), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testOrderID.AsString()), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/define/transaction_request_test.go b/x/orders/transactions/define/transaction_request_test.go index 589a66a21..802e041f2 100644 --- a/x/orders/transactions/define/transaction_request_test.go +++ b/x/orders/transactions/define/transaction_request_test.go @@ -115,7 +115,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/deputize/transaction_request_test.go b/x/orders/transactions/deputize/transaction_request_test.go index 363512809..44375d68a 100644 --- a/x/orders/transactions/deputize/transaction_request_test.go +++ b/x/orders/transactions/deputize/transaction_request_test.go @@ -120,7 +120,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString(), maintainedPropertyString, true, true, true, true, true}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString(), maintainedPropertyString, true, true, true, true, true), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString(), maintainedPropertyString, true, true, true, true, true}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString(), maintainedPropertyString, true, true, true, true, true), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/get/transaction_request_test.go b/x/orders/transactions/get/transaction_request_test.go index 528f0c717..c55d58204 100644 --- a/x/orders/transactions/get/transaction_request_test.go +++ b/x/orders/transactions/get/transaction_request_test.go @@ -100,7 +100,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{testBaseRequest, testFromID.AsString(), testOrderID.AsString()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/immediate/transaction_request_test.go b/x/orders/transactions/immediate/transaction_request_test.go index 9b8690fa6..c925531e4 100644 --- a/x/orders/transactions/immediate/transaction_request_test.go +++ b/x/orders/transactions/immediate/transaction_request_test.go @@ -140,7 +140,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/make/transaction_request_test.go b/x/orders/transactions/make/transaction_request_test.go index 50e78dcf9..2562c7321 100644 --- a/x/orders/transactions/make/transaction_request_test.go +++ b/x/orders/transactions/make/transaction_request_test.go @@ -138,7 +138,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), testClassificationID.AsString(), testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), expiresIn, makerSplit.String(), takerSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/modify/transaction_request_test.go b/x/orders/transactions/modify/transaction_request_test.go index 6770f4716..c8b891529 100644 --- a/x/orders/transactions/modify/transaction_request_test.go +++ b/x/orders/transactions/modify/transaction_request_test.go @@ -122,7 +122,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString(), takerSplit.String(), makerSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{testBaseRequest, testFromID.AsString(), testOrderID.AsString(), takerSplit.String(), makerSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testOrderID.AsString(), takerSplit.String(), makerSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{testBaseRequest, testFromID.AsString(), testOrderID.AsString(), takerSplit.String(), makerSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/put/transaction_request_test.go b/x/orders/transactions/put/transaction_request_test.go index e472efda3..102bfd2cb 100644 --- a/x/orders/transactions/put/transaction_request_test.go +++ b/x/orders/transactions/put/transaction_request_test.go @@ -126,7 +126,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), makerSplit.String(), takerSplit.String(), expiryHeight}, args{cliCommand, baseHelpers.TestClientContext}, newTransactionRequest(testBaseRequest, testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), makerSplit.String(), takerSplit.String(), expiryHeight), false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), makerSplit.String(), takerSplit.String(), expiryHeight}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, newTransactionRequest(testBaseRequest, testFromID.AsString(), makerAssetID.AsString(), takerAssetID.AsString(), makerSplit.String(), takerSplit.String(), expiryHeight), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/revoke/transaction_request_test.go b/x/orders/transactions/revoke/transaction_request_test.go index af482f865..c4c2b53ee 100644 --- a/x/orders/transactions/revoke/transaction_request_test.go +++ b/x/orders/transactions/revoke/transaction_request_test.go @@ -99,7 +99,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString()}, false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{testBaseRequest, testFromID.AsString(), testFromID.AsString(), testClassificationID.AsString()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/orders/transactions/take/transaction_request_test.go b/x/orders/transactions/take/transaction_request_test.go index cfe2de3a7..d650a8da5 100644 --- a/x/orders/transactions/take/transaction_request_test.go +++ b/x/orders/transactions/take/transaction_request_test.go @@ -101,7 +101,7 @@ func Test_transactionRequest_FromCLI(t *testing.T) { want helpers.TransactionRequest wantErr bool }{ - {"+ve", fields{testBaseRequest, testFromID.AsString(), takerSplit.String(), testOrderID.AsString()}, args{cliCommand, baseHelpers.TestClientContext}, transactionRequest{testBaseRequest, testFromID.AsString(), takerSplit.String(), testOrderID.AsString()}, false}, + {"+ve", fields{testBaseRequest, testFromID.AsString(), takerSplit.String(), testOrderID.AsString()}, args{cliCommand, client.Context{}.WithCodec(baseHelpers.CodecPrototype())}, transactionRequest{testBaseRequest, testFromID.AsString(), takerSplit.String(), testOrderID.AsString()}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/splits/queries/balances/query_request_test.go b/x/splits/queries/balances/query_request_test.go index 1c002b67f..c80fe16a1 100644 --- a/x/splits/queries/balances/query_request_test.go +++ b/x/splits/queries/balances/query_request_test.go @@ -152,7 +152,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testIdentityID.(*baseIDs.IdentityID)}, args{cliCommand, base.TestClientContext}, newQueryRequest(testIdentityID), false}, + {"+ve", fields{testIdentityID.(*baseIDs.IdentityID)}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newQueryRequest(testIdentityID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/splits/queries/split/query_request_test.go b/x/splits/queries/split/query_request_test.go index b6eb975ef..d1fc120e4 100644 --- a/x/splits/queries/split/query_request_test.go +++ b/x/splits/queries/split/query_request_test.go @@ -163,7 +163,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{splitID}, args{cliCommand, base.TestClientContext}, newQueryRequest(splitID), false}, + {"+ve", fields{splitID}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newQueryRequest(splitID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/splits/queries/supply/query_request_test.go b/x/splits/queries/supply/query_request_test.go index 5967d403e..8739754e0 100644 --- a/x/splits/queries/supply/query_request_test.go +++ b/x/splits/queries/supply/query_request_test.go @@ -153,7 +153,7 @@ func Test_queryRequest_FromCLI(t *testing.T) { want helpers.QueryRequest wantErr bool }{ - {"+ve", fields{testAssetID}, args{cliCommand, base.TestClientContext}, newQueryRequest(testAssetID), false}, + {"+ve", fields{testAssetID}, args{cliCommand, client.Context{}.WithCodec(base.CodecPrototype())}, newQueryRequest(testAssetID), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From 9ada41f4624168ae3f4399a35f7aca905e21fc5c Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 13 Mar 2024 23:20:04 +0530 Subject: [PATCH 07/57] fix(validatable_parameter): adding nic checks --- helpers/base/validatable_parameter.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/helpers/base/validatable_parameter.go b/helpers/base/validatable_parameter.go index 9e667f13c..177005353 100644 --- a/helpers/base/validatable_parameter.go +++ b/helpers/base/validatable_parameter.go @@ -18,13 +18,18 @@ func (validatableParameter validatableParameter) GetParameter() parameters.Param return validatableParameter.parameter } func (validatableParameter validatableParameter) Mutate(data data.Data) helpers.ValidatableParameter { - validatableParameter.parameter = validatableParameter.parameter.Mutate(data) + if data != nil { + validatableParameter.parameter = validatableParameter.parameter.Mutate(data) + } return validatableParameter } func (validatableParameter validatableParameter) GetValidator() func(i interface{}) error { return validatableParameter.validator } func (validatableParameter validatableParameter) Validate() error { + if validatableParameter.validator == nil { + return nil + } return validatableParameter.validator(validatableParameter.parameter) } From bc0f95188e2f671c3a3a0c76ea970eb5ba395046 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 13 Mar 2024 23:20:32 +0530 Subject: [PATCH 08/57] feat(validatable_parameter): adding unit test cases --- helpers/base/validatable_parameter_test.go | 226 +++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 helpers/base/validatable_parameter_test.go diff --git a/helpers/base/validatable_parameter_test.go b/helpers/base/validatable_parameter_test.go new file mode 100644 index 000000000..6cf58be2b --- /dev/null +++ b/helpers/base/validatable_parameter_test.go @@ -0,0 +1,226 @@ +package base + +import ( + "fmt" + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/schema/go/data" + base4 "github.com/AssetMantle/schema/go/data/base" + base3 "github.com/AssetMantle/schema/go/ids/base" + "github.com/AssetMantle/schema/go/parameters" + "github.com/AssetMantle/schema/go/parameters/base" + base2 "github.com/AssetMantle/schema/go/properties/base" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestNewValidatableParameter(t *testing.T) { + tests := []struct { + name string + param parameters.Parameter + validateFunc func(i interface{}) error + wantErr error + }{ + { + name: "Test invalid input", + param: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validateFunc: func(i interface{}) error { return fmt.Errorf("error") }, + wantErr: fmt.Errorf("error"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + vp := NewValidatableParameter(tt.param, tt.validateFunc) + if err := vp.Validate(); (err != nil) != (tt.wantErr != nil) { + t.Errorf("NewValidatableParameter() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_validatableParameter_GetParameter(t *testing.T) { + type fields struct { + parameter parameters.Parameter + validator func(i interface{}) error + } + tests := []struct { + name string + fields fields + want parameters.Parameter + }{ + { + name: "Test valid input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return nil }, + }, + want: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + }, + { + name: "Test nil input", + fields: fields{ + parameter: nil, + validator: nil, + }, + want: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + validatableParameter := validatableParameter{ + parameter: tt.fields.parameter, + validator: tt.fields.validator, + } + assert.Equalf(t, tt.want, validatableParameter.GetParameter(), "GetParameter()") + }) + } +} + +func Test_validatableParameter_GetValidator(t *testing.T) { + type fields struct { + parameter parameters.Parameter + validator func(i interface{}) error + } + tests := []struct { + name string + fields fields + want func(i interface{}) error + }{ + { + name: "Test valid input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { + if i != base4.NewStringData("valid") { + return fmt.Errorf("error") + } + return nil + }, + }, + want: func(i interface{}) error { + if i != base4.NewStringData("valid") { + return fmt.Errorf("error") + } + return nil + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + validatableParameter := validatableParameter{ + parameter: tt.fields.parameter, + validator: tt.fields.validator, + } + assert.Equalf(t, tt.want(base4.NewStringData("aa")), validatableParameter.GetValidator()(base4.NewStringData("aa")), "GetValidator()") + }) + } +} + +func Test_validatableParameter_Mutate(t *testing.T) { + type fields struct { + parameter parameters.Parameter + validator func(i interface{}) error + } + type args struct { + data data.Data + } + tests := []struct { + name string + fields fields + args args + want helpers.ValidatableParameter + }{ + { + name: "Test valid input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return nil }, + }, + args: args{ + data: base4.NewStringData("mutatedTestData"), + }, + want: validatableParameter{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("mutatedTestData"))), + validator: func(i interface{}) error { return nil }, + }, + }, + { + name: "Test nil input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return nil }, + }, + args: args{ + data: nil, + }, + want: validatableParameter{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return nil }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + validatableParameter := validatableParameter{ + parameter: tt.fields.parameter, + validator: tt.fields.validator, + } + assert.Equalf(t, tt.want.GetParameter().String(), validatableParameter.Mutate(tt.args.data).GetParameter().String(), "Mutate(%v)", tt.args.data) + }) + } +} + +func Test_validatableParameter_Validate(t *testing.T) { + type fields struct { + parameter parameters.Parameter + validator func(i interface{}) error + } + tests := []struct { + name string + fields fields + wantErr assert.ErrorAssertionFunc + }{ + { + name: "Test invalid input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return fmt.Errorf("error") }, + }, + wantErr: assert.Error, + }, + { + name: "Test valid input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: func(i interface{}) error { return nil }, + }, + wantErr: assert.NoError, + }, + { + name: "Test nil input", + fields: fields{ + parameter: base.NewParameter(base2.NewMetaProperty(base3.NewStringID("testName"), base4.NewStringData("testData"))), + validator: nil, + }, + wantErr: assert.NoError, + }, + { + name: "Test nil parameter and validator", + fields: fields{ + parameter: nil, + validator: nil, + }, + wantErr: assert.NoError, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + validatableParameter := validatableParameter{ + parameter: tt.fields.parameter, + validator: tt.fields.validator, + } + tt.wantErr(t, validatableParameter.Validate(), fmt.Sprintf("Validate()")) + }) + } +} From 9cb2c94998c1e84e806ae21db2459e54b444eb1a Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 14 Mar 2024 19:23:21 +0530 Subject: [PATCH 09/57] fix(auxiliaries): adding nil checks --- helpers/base/auxiliaries.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/helpers/base/auxiliaries.go b/helpers/base/auxiliaries.go index 9c04764e1..4c045c17c 100644 --- a/helpers/base/auxiliaries.go +++ b/helpers/base/auxiliaries.go @@ -3,7 +3,9 @@ package base -import "github.com/AssetMantle/modules/helpers" +import ( + "github.com/AssetMantle/modules/helpers" +) type auxiliaries struct { auxiliaryList []helpers.Auxiliary @@ -25,6 +27,19 @@ func (auxiliaries auxiliaries) Get() []helpers.Auxiliary { } func NewAuxiliaries(auxiliaryList ...helpers.Auxiliary) helpers.Auxiliaries { + for i, auxiliary := range auxiliaryList { + + if auxiliary == nil { + panic("nil auxiliary") + } + + for j, checkAuxiliary := range auxiliaryList { + if i != j && auxiliary.GetName() == checkAuxiliary.GetName() { + panic("repeated auxiliary") + } + } + } + return auxiliaries{ auxiliaryList: auxiliaryList, } From 16a3fb46fe6770f779e858cc73550876c593fd4a Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 14 Mar 2024 19:23:39 +0530 Subject: [PATCH 10/57] fix(auxiliary): adding nil checks --- helpers/base/auxiliary.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/helpers/base/auxiliary.go b/helpers/base/auxiliary.go index 8db3616b3..459b3ee63 100644 --- a/helpers/base/auxiliary.go +++ b/helpers/base/auxiliary.go @@ -20,6 +20,15 @@ func (auxiliary auxiliary) Initialize(mapper helpers.Mapper, parameterManager he return auxiliary } func NewAuxiliary(name string, keeperPrototype func() helpers.AuxiliaryKeeper) helpers.Auxiliary { + if name == "" { + panic("empty name") + } + + if keeperPrototype == nil { + panic("nil keeper prototype") + + } + return auxiliary{ name: name, keeperPrototype: keeperPrototype, From e0a72555a1549b626437c8b7ec488c4f90e0225a Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 14 Mar 2024 19:26:54 +0530 Subject: [PATCH 11/57] chore(helpers): Update tests and add error handling to auxiliary module Added error handling for the auxiliary module and expanded test coverage for better integrity checking and robustness. Improved tests in the helpers/base package, especially for auxiliaries and cli_flag. Updated error handling and validations for auxiliary initializations and operations to prevent panics and ensure data integrity. --- helpers/base/auxiliaries_test.go | 30 ++- helpers/base/auxiliary_test.go | 228 ++++++++++++------ helpers/base/cli_flag_test.go | 391 +++++++++++++++++++++++++++++-- 3 files changed, 548 insertions(+), 101 deletions(-) diff --git a/helpers/base/auxiliaries_test.go b/helpers/base/auxiliaries_test.go index 3c56a65e1..45845c07d 100644 --- a/helpers/base/auxiliaries_test.go +++ b/helpers/base/auxiliaries_test.go @@ -131,9 +131,10 @@ func TestNewAuxiliaries(t *testing.T) { auxiliaryList []helpers.Auxiliary } tests := []struct { - name string - args args - want helpers.Auxiliaries + name string + args args + want helpers.Auxiliaries + panic bool }{ { name: "Empty AuxiliaryList", @@ -158,9 +159,21 @@ func TestNewAuxiliaries(t *testing.T) { args: args{ auxiliaryList: []helpers.Auxiliary{nil}, }, - want: auxiliaries{ - auxiliaryList: []helpers.Auxiliary{nil}, + panic: true, + }, + { + name: "Nil Auxiliary in list", + args: args{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, nil, mockAuxiliary{randomUniqueIdentifiers[1]}}, + }, + panic: true, + }, + { + name: "Repeated Auxiliary", + args: args{ + auxiliaryList: []helpers.Auxiliary{mockAuxiliary{randomUniqueIdentifiers[0]}, mockAuxiliary{randomUniqueIdentifiers[0]}}, }, + panic: true, }, } for _, tt := range tests { @@ -169,7 +182,12 @@ func TestNewAuxiliaries(t *testing.T) { for i, v := range tt.args.auxiliaryList { auxListInterface[i] = v } - assert.Equalf(t, tt.want, NewAuxiliaries(tt.args.auxiliaryList...), "NewAuxiliaries(%v)", auxListInterface...) + if tt.panic { + assert.Panicsf(t, func() { NewAuxiliaries(tt.args.auxiliaryList...) }, "NewAuxiliaries(%v)", auxListInterface...) + return + } else { + assert.Equalf(t, tt.want, NewAuxiliaries(tt.args.auxiliaryList...), "NewAuxiliaries(%v)", auxListInterface...) + } }) } } diff --git a/helpers/base/auxiliary_test.go b/helpers/base/auxiliary_test.go index 97573da99..fbeb132d2 100644 --- a/helpers/base/auxiliary_test.go +++ b/helpers/base/auxiliary_test.go @@ -4,6 +4,9 @@ package base import ( + context2 "context" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/kv" "github.com/stretchr/testify/assert" "golang.org/x/net/context" "testing" @@ -11,45 +14,92 @@ import ( "github.com/AssetMantle/modules/helpers" ) +type dummyAuxiliaryKeeper struct{} + +func (dummyAuxiliaryKeeper *dummyAuxiliaryKeeper) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ []interface{}) helpers.Keeper { + return dummyAuxiliaryKeeper +} +func (dummyAuxiliaryKeeper *dummyAuxiliaryKeeper) Help(_ context.Context, _ helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + return nil, nil +} + +type dummyMapper struct{} + +func (dummyMapper dummyMapper) NewCollection(_ context2.Context) helpers.Collection { + return nil +} +func (dummyMapper dummyMapper) Upsert(_ context2.Context, _ helpers.Record) { +} +func (dummyMapper dummyMapper) Read(_ context2.Context, _ helpers.Key) helpers.Record { + return nil +} +func (dummyMapper dummyMapper) Delete(_ context2.Context, _ helpers.Key) { +} +func (dummyMapper dummyMapper) FetchAll(_ context2.Context) []helpers.Record { + return nil +} +func (dummyMapper dummyMapper) Iterate(_ context2.Context, _ helpers.Key, _ func(helpers.Record) bool) { +} + +func (dummyMapper dummyMapper) IterateAll(_ context2.Context, _ func(helpers.Record) bool) { +} + +func (dummyMapper dummyMapper) IteratePaginated(_ context2.Context, _ helpers.Key, _ int32, _ func(helpers.Record) bool) { +} +func (dummyMapper dummyMapper) StoreDecoder(_ kv.Pair, _ kv.Pair) string { + return "" +} +func (dummyMapper dummyMapper) Initialize(_ *sdkTypes.KVStoreKey) helpers.Mapper { + return nil +} +func (dummyMapper dummyMapper) Get(_ string) (interface{}, error) { + return nil, nil +} +func (dummyMapper dummyMapper) Set(_ string, _ interface{}) error { + return nil +} + func TestGetName(t *testing.T) { tests := []struct { name string input string expect string + panic bool }{ { - "Valid name", - "sampleName", - "sampleName", + name: "Valid name", + input: "sampleName", + expect: "sampleName", }, { - "Empty name", - "", - "", + name: "Empty name", + input: "", + panic: true, }, { - "Whitespace name", - " ", - " ", + name: "Whitespace name", + input: " ", + expect: " ", }, { - "Special character in name", - "@#$-_=+!", - "@#$-_=+!", + name: "Special character in name", + input: "@#$-_=+!", + expect: "@#$-_=+!", }, } - // Create mock KeeperPrototype function - mockKeeperPrototype := func() helpers.AuxiliaryKeeper { - return nil - } - for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - aux := NewAuxiliary(tt.input, mockKeeperPrototype) - if got := aux.GetName(); got != tt.expect { - t.Errorf("GetName() = %v, want = %v", got, tt.expect) + if tt.panic { + + } + if tt.panic { + assert.Panics(t, func() { NewAuxiliary(tt.input, func() helpers.AuxiliaryKeeper { return nil }) }) + } else { + if NewAuxiliary(tt.input, func() helpers.AuxiliaryKeeper { return nil }).GetName() != tt.expect { + t.Errorf("GetName() = %v, want = %v", NewAuxiliary(tt.input, func() helpers.AuxiliaryKeeper { return nil }).GetName(), tt.expect) + } } }) } @@ -88,78 +138,106 @@ func TestGetKeeper(t *testing.T) { } } -func TestInitialize(t *testing.T) { - // Define the test cases - testCases := []struct { - name string - auxiliaryName string - keeperPrototype func() helpers.AuxiliaryKeeper - mapper helpers.Mapper - parameterManager helpers.ParameterManager - auxiliaryKeepers []interface{} - expectedAuxiliary helpers.Auxiliary +func Test_auxiliary_Initialize(t *testing.T) { + type fields struct { + name string + auxiliaryKeeper helpers.AuxiliaryKeeper + keeperPrototype func() helpers.AuxiliaryKeeper + } + type args struct { + mapper helpers.Mapper + parameterManager helpers.ParameterManager + auxiliaryKeepers []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Auxiliary }{ { - name: "Valid case", - auxiliaryName: "TestAuxiliary", - keeperPrototype: func() helpers.AuxiliaryKeeper { return nil }, - mapper: nil, - parameterManager: nil, - auxiliaryKeepers: []interface{}{ /*...*/ }, - expectedAuxiliary: &auxiliary{ // Adjust as per actual implementation - name: "TestAuxiliary", - keeperPrototype: func() helpers.AuxiliaryKeeper { return nil }, - auxiliaryKeeper: nil, + name: "Test valid input", + fields: fields{ + name: "testName", + auxiliaryKeeper: &dummyAuxiliaryKeeper{}, + keeperPrototype: func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, + }, + args: args{ + mapper: dummyMapper{}, + parameterManager: nil, + auxiliaryKeepers: []interface{}{&dummyAuxiliaryKeeper{}}, + }, + want: auxiliary{ + name: "testName", + auxiliaryKeeper: &dummyAuxiliaryKeeper{}, + keeperPrototype: func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, }, }, - // Add more test cases for all corner cases } - - // Run the tests - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Define the auxiliary - auxiliary := NewAuxiliary(tc.auxiliaryName, tc.keeperPrototype) - - // Call initialize method - gotAuxiliary := auxiliary.Initialize(tc.mapper, tc.parameterManager, tc.auxiliaryKeepers...) - - // Assert that the returned Auxiliary is the expected one - assert.Equal(t, tc.expectedAuxiliary, gotAuxiliary) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliary := auxiliary{ + name: tt.fields.name, + auxiliaryKeeper: tt.fields.auxiliaryKeeper, + keeperPrototype: tt.fields.keeperPrototype, + } + var auxiliaryKeepers []interface{} + for _, v := range tt.args.auxiliaryKeepers { + auxiliaryKeepers = append(auxiliaryKeepers, v) + } + assert.Equalf(t, tt.want.GetKeeper(), auxiliary.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaryKeepers...).GetKeeper(), "Initialize(%v, %v, %v)", tt.args.mapper, tt.args.parameterManager, auxiliaryKeepers) + assert.Equalf(t, tt.want.GetName(), auxiliary.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaryKeepers...).GetName(), "Initialize(%v, %v, %v)", tt.args.mapper, tt.args.parameterManager, auxiliaryKeepers) }) } } func TestNewAuxiliary(t *testing.T) { - var tests = []struct { + type args struct { name string keeperPrototype func() helpers.AuxiliaryKeeper - expectedName string - keeperTest bool + } + tests := []struct { + name string + args args + want helpers.Auxiliary + panics bool }{ - {"test1", func() helpers.AuxiliaryKeeper { return nil }, "test1", false}, - {"", func() helpers.AuxiliaryKeeper { return nil }, "", false}, - {"test3", func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, "test3", true}, + { + name: "Test valid input", + args: args{ + name: "testName", + keeperPrototype: func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, + }, + want: auxiliary{ + name: "testName", + keeperPrototype: func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, + }, + }, + { + name: "Test empty name", + args: args{ + name: "", + keeperPrototype: func() helpers.AuxiliaryKeeper { return &dummyAuxiliaryKeeper{} }, + }, + panics: true, + }, + { + name: "Test nil keeper prototype", + args: args{ + name: "testName", + keeperPrototype: nil, + }, + panics: true, + }, } - for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - auxiliary := NewAuxiliary(tt.name, tt.keeperPrototype) - if gotName := auxiliary.GetName(); gotName != tt.expectedName { - t.Errorf("NewAuxiliary().GetName() = %v, expected %v", gotName, tt.expectedName) - } - if gotKeeper := auxiliary.GetKeeper(); (gotKeeper != nil) != tt.keeperTest { - t.Errorf("NewAuxiliary().GetKeeper() existence = %v, expected %v", gotKeeper != nil, tt.keeperTest) + if tt.panics { + assert.Panics(t, func() { NewAuxiliary(tt.args.name, tt.args.keeperPrototype) }) + } else { + assert.Equalf(t, tt.want.GetName(), NewAuxiliary(tt.args.name, tt.args.keeperPrototype).GetName(), "NewAuxiliary(%v, %v)", tt.args.name, tt.args.keeperPrototype) + assert.Equalf(t, tt.want.GetKeeper(), NewAuxiliary(tt.args.name, tt.args.keeperPrototype).GetKeeper(), "NewAuxiliary(%v, %v)", tt.args.name, tt.args.keeperPrototype) } }) } } - -type dummyAuxiliaryKeeper struct{} - -func (d *dummyAuxiliaryKeeper) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ []interface{}) helpers.Keeper { - return nil -} -func (d *dummyAuxiliaryKeeper) Help(_ context.Context, _ helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { - return nil, nil -} diff --git a/helpers/base/cli_flag_test.go b/helpers/base/cli_flag_test.go index ae384f2d3..9e18bb9ce 100644 --- a/helpers/base/cli_flag_test.go +++ b/helpers/base/cli_flag_test.go @@ -4,29 +4,380 @@ package base import ( - "testing" - + "github.com/AssetMantle/modules/helpers" "github.com/spf13/cobra" - "github.com/stretchr/testify/require" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "testing" ) -func Test_CliFlag(t *testing.T) { - testCliFlag := NewCLIFlag("name", "value", ",usage") - require.Panics(t, func() { - NewCLIFlag("name", struct{}{}, ",usage").Register(&cobra.Command{}) - }) - // GetName method test - require.Equal(t, "name", testCliFlag.GetName()) - // GetSupply method test - require.Equal(t, "value", testCliFlag.GetValue()) +func TestNewCLIFlag(t *testing.T) { + type args struct { + name string + value interface{} + usage string + } + tests := []struct { + name string + args args + want helpers.CLIFlag + }{ + {"+ve", args{"name", "value", ",usage"}, cliFlag{"name", "value", ",usage"}}, + {"nil", args{"", nil, ""}, cliFlag{"", nil, ""}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equalf(t, tt.want, NewCLIFlag(tt.args.name, tt.args.value, tt.args.usage), "NewCLIFlag(%v, %v, %v)", tt.args.name, tt.args.value, tt.args.usage) + }) + } +} - // ReadCLIValue method test - require.Equal(t, "", testCliFlag.ReadCLIValue()) - require.Equal(t, int64(0), NewCLIFlag("name", int64(-1), ",usage").ReadCLIValue()) - require.Equal(t, 0, NewCLIFlag("name", 123, ",usage").ReadCLIValue()) - require.Equal(t, false, NewCLIFlag("name", false, ",usage").ReadCLIValue()) - require.Panics(t, func() { - NewCLIFlag("name", struct{}{}, ",usage").ReadCLIValue() - }) +func Test_cliFlag_GetName(t *testing.T) { + type fields struct { + name string + value interface{} + usage string + } + tests := []struct { + name string + fields fields + want string + }{ + { + name: "Test GetName", + fields: fields{ + name: "test", + value: "test", + usage: "test", + }, + want: "test", + }, + { + name: "Test GetName", + fields: fields{ + name: "", + value: nil, + usage: "", + }, + want: "", + }, + { + name: "Test GetName", + fields: fields{ + name: "test", + value: nil, + usage: "", + }, + want: "test", + }, + { + name: "Test GetName", + fields: fields{ + name: "", + value: "test", + usage: "", + }, + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliFlag := cliFlag{ + name: tt.fields.name, + value: tt.fields.value, + usage: tt.fields.usage, + } + assert.Equalf(t, tt.want, cliFlag.GetName(), "GetName()") + }) + } +} + +func Test_cliFlag_GetValue(t *testing.T) { + type fields struct { + name string + value interface{} + usage string + } + tests := []struct { + name string + fields fields + want interface{} + }{ + { + name: "Test GetValue", + fields: fields{ + name: "test", + value: "test", + usage: "test", + }, + want: "test", + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: nil, + usage: "", + }, + want: nil, + }, + { + name: "Test GetValue", + fields: fields{ + name: "test", + value: nil, + usage: "", + }, + want: nil, + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: "test", + usage: "", + }, + want: "test", + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: 1, + usage: "", + }, + want: 1, + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: int64(1), + usage: "", + }, + want: int64(1), + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: false, + usage: "", + }, + want: false, + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: true, + usage: "", + }, + want: true, + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: struct{}{}, + usage: "", + }, + want: struct{}{}, + }, + { + name: "Test GetValue", + fields: fields{ + name: "", + value: nil, + usage: "", + }, + want: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliFlag := cliFlag{ + name: tt.fields.name, + value: tt.fields.value, + usage: tt.fields.usage, + } + assert.Equalf(t, tt.want, cliFlag.GetValue(), "GetValue()") + }) + } +} + +func Test_cliFlag_ReadCLIValue(t *testing.T) { + type fields struct { + name string + value interface{} + usage string + } + tests := []struct { + name string + fields fields + want interface{} + panics bool + }{ + { + name: "Test ReadCLIValue", + fields: fields{ + name: "test", + value: "test", + usage: "test", + }, + want: "test", + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: nil, + usage: "", + }, + panics: true, + }, { + name: "Test ReadCLIValue", + fields: fields{ + name: "test", + value: nil, + usage: "", + }, + panics: true, + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: "test", + usage: "", + }, + want: "test", + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: 1, + usage: "", + }, + want: 1, + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: int64(1), + usage: "", + }, + want: int64(1), + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: false, + usage: "", + }, + want: false, + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: true, + usage: "", + }, + want: true, + }, + { + name: "Test ReadCLIValue", + fields: fields{ + name: "", + value: struct{}{}, + usage: "", + }, + panics: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliFlag := cliFlag{ + name: tt.fields.name, + value: tt.fields.value, + usage: tt.fields.usage, + } + viper.Set(tt.fields.name, tt.fields.value) + if tt.panics { + assert.Panics(t, func() { cliFlag.ReadCLIValue() }, "ReadCLIValue()") + return + } else { + assert.Equalf(t, tt.want, cliFlag.ReadCLIValue(), "ReadCLIValue()") + } + }) + } +} +func Test_cliFlag_Register(t *testing.T) { + type fields struct { + name string + value interface{} + usage string + } + type args struct { + command *cobra.Command + } + tests := []struct { + name string + fields fields + args args + panics bool + }{ + { + name: "Test Register", + fields: fields{ + name: "test", + value: "test", + usage: "test", + }, + args: args{ + command: &cobra.Command{}, + }, + }, + { + name: "Test Register", + fields: fields{ + name: "", + value: nil, + usage: "", + }, + args: args{ + command: &cobra.Command{}, + }, + panics: true, + }, + { + name: "Test Register", + fields: fields{ + name: "test", + value: nil, + usage: "", + }, + args: args{ + command: &cobra.Command{}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliFlag := cliFlag{ + name: tt.fields.name, + value: tt.fields.value, + usage: tt.fields.usage, + } + if tt.panics { + assert.Panics(t, func() { cliFlag.Register(tt.args.command) }, "Register()") + return + } + }) + } } From f79a53fa65edb3d32df2c3b29b66d622803939bc Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 18 Mar 2024 16:59:10 +0530 Subject: [PATCH 12/57] feat(message): adding GetFromAddress method to message interface --- helpers/message.go | 1 + x/assets/transactions/burn/message.go | 7 +++++++ x/assets/transactions/define/message.go | 7 +++++++ x/assets/transactions/deputize/message.go | 7 +++++++ x/assets/transactions/mint/message.go | 7 +++++++ x/assets/transactions/mutate/message.go | 7 +++++++ x/assets/transactions/renumerate/message.go | 7 +++++++ x/assets/transactions/revoke/message.go | 7 +++++++ x/assets/transactions/send/message.go | 7 +++++++ x/assets/transactions/unwrap/message.go | 7 +++++++ x/assets/transactions/wrap/message.go | 7 +++++++ x/identities/transactions/define/message.go | 7 +++++++ x/identities/transactions/deputize/message.go | 7 +++++++ x/identities/transactions/issue/message.go | 7 +++++++ x/identities/transactions/name/message.go | 7 +++++++ x/identities/transactions/provision/message.go | 7 +++++++ x/identities/transactions/quash/message.go | 7 +++++++ x/identities/transactions/revoke/message.go | 7 +++++++ x/identities/transactions/unprovision/message.go | 7 +++++++ x/identities/transactions/update/message.go | 7 +++++++ x/metas/transactions/reveal/message.go | 7 +++++++ x/orders/transactions/cancel/message.go | 7 +++++++ x/orders/transactions/define/message.go | 7 +++++++ x/orders/transactions/deputize/message.go | 7 +++++++ x/orders/transactions/get/message.go | 7 +++++++ x/orders/transactions/immediate/message.go | 7 +++++++ x/orders/transactions/make/message.go | 7 +++++++ x/orders/transactions/modify/message.go | 7 +++++++ x/orders/transactions/put/message.go | 7 +++++++ x/orders/transactions/revoke/message.go | 7 +++++++ x/orders/transactions/take/message.go | 7 +++++++ 31 files changed, 211 insertions(+) diff --git a/helpers/message.go b/helpers/message.go index 1aa308694..97d9ebc39 100644 --- a/helpers/message.go +++ b/helpers/message.go @@ -14,5 +14,6 @@ type Message interface { RegisterLegacyAminoCodec(*codec.LegacyAmino) RegisterInterface(types.InterfaceRegistry) Type() string + GetFromAddress() sdkTypes.AccAddress sdkTypes.Msg } diff --git a/x/assets/transactions/burn/message.go b/x/assets/transactions/burn/message.go index 04a8c41ca..72ad65ebe 100644 --- a/x/assets/transactions/burn/message.go +++ b/x/assets/transactions/burn/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/define/message.go b/x/assets/transactions/define/message.go index 3524ebd06..c5b7608f1 100644 --- a/x/assets/transactions/define/message.go +++ b/x/assets/transactions/define/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/deputize/message.go b/x/assets/transactions/deputize/message.go index 4291c3a29..58b22e296 100644 --- a/x/assets/transactions/deputize/message.go +++ b/x/assets/transactions/deputize/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/mint/message.go b/x/assets/transactions/mint/message.go index fdb9e0583..b2d9250b0 100644 --- a/x/assets/transactions/mint/message.go +++ b/x/assets/transactions/mint/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/mutate/message.go b/x/assets/transactions/mutate/message.go index aa033dd9f..38b9ee6c4 100644 --- a/x/assets/transactions/mutate/message.go +++ b/x/assets/transactions/mutate/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/renumerate/message.go b/x/assets/transactions/renumerate/message.go index 2f75eec06..f4f171847 100644 --- a/x/assets/transactions/renumerate/message.go +++ b/x/assets/transactions/renumerate/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/revoke/message.go b/x/assets/transactions/revoke/message.go index 43ff83c67..54917e789 100644 --- a/x/assets/transactions/revoke/message.go +++ b/x/assets/transactions/revoke/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/send/message.go b/x/assets/transactions/send/message.go index 85001b561..2912d5ad0 100644 --- a/x/assets/transactions/send/message.go +++ b/x/assets/transactions/send/message.go @@ -18,6 +18,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/unwrap/message.go b/x/assets/transactions/unwrap/message.go index 504a363ac..36ea47023 100644 --- a/x/assets/transactions/unwrap/message.go +++ b/x/assets/transactions/unwrap/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/assets/transactions/wrap/message.go b/x/assets/transactions/wrap/message.go index 97f0d64b1..dacf68abd 100644 --- a/x/assets/transactions/wrap/message.go +++ b/x/assets/transactions/wrap/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/define/message.go b/x/identities/transactions/define/message.go index 3524ebd06..c5b7608f1 100644 --- a/x/identities/transactions/define/message.go +++ b/x/identities/transactions/define/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/deputize/message.go b/x/identities/transactions/deputize/message.go index 99a052aaa..a3150f59c 100644 --- a/x/identities/transactions/deputize/message.go +++ b/x/identities/transactions/deputize/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/issue/message.go b/x/identities/transactions/issue/message.go index fe35b04dc..050a59798 100644 --- a/x/identities/transactions/issue/message.go +++ b/x/identities/transactions/issue/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/name/message.go b/x/identities/transactions/name/message.go index 419df9155..c675286be 100644 --- a/x/identities/transactions/name/message.go +++ b/x/identities/transactions/name/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/provision/message.go b/x/identities/transactions/provision/message.go index 23f45ce8b..a4bf18874 100644 --- a/x/identities/transactions/provision/message.go +++ b/x/identities/transactions/provision/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/quash/message.go b/x/identities/transactions/quash/message.go index 18a3bfc05..4e7de5135 100644 --- a/x/identities/transactions/quash/message.go +++ b/x/identities/transactions/quash/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/revoke/message.go b/x/identities/transactions/revoke/message.go index 43ff83c67..54917e789 100644 --- a/x/identities/transactions/revoke/message.go +++ b/x/identities/transactions/revoke/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/unprovision/message.go b/x/identities/transactions/unprovision/message.go index 38eba8daf..b9c91fe0b 100644 --- a/x/identities/transactions/unprovision/message.go +++ b/x/identities/transactions/unprovision/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/identities/transactions/update/message.go b/x/identities/transactions/update/message.go index 82a9d8abf..f373fda60 100644 --- a/x/identities/transactions/update/message.go +++ b/x/identities/transactions/update/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/metas/transactions/reveal/message.go b/x/metas/transactions/reveal/message.go index 931c1ea43..6dcd6384a 100644 --- a/x/metas/transactions/reveal/message.go +++ b/x/metas/transactions/reveal/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/cancel/message.go b/x/orders/transactions/cancel/message.go index 0dd7d031b..d542f7925 100644 --- a/x/orders/transactions/cancel/message.go +++ b/x/orders/transactions/cancel/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/define/message.go b/x/orders/transactions/define/message.go index 3524ebd06..c5b7608f1 100644 --- a/x/orders/transactions/define/message.go +++ b/x/orders/transactions/define/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/deputize/message.go b/x/orders/transactions/deputize/message.go index 1891323ff..70bc9ee7c 100644 --- a/x/orders/transactions/deputize/message.go +++ b/x/orders/transactions/deputize/message.go @@ -19,6 +19,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/get/message.go b/x/orders/transactions/get/message.go index dca898600..4403a368f 100644 --- a/x/orders/transactions/get/message.go +++ b/x/orders/transactions/get/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/immediate/message.go b/x/orders/transactions/immediate/message.go index aab259d0f..a6848825f 100644 --- a/x/orders/transactions/immediate/message.go +++ b/x/orders/transactions/immediate/message.go @@ -22,6 +22,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/make/message.go b/x/orders/transactions/make/message.go index f5568a766..95fee8ef7 100644 --- a/x/orders/transactions/make/message.go +++ b/x/orders/transactions/make/message.go @@ -22,6 +22,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/modify/message.go b/x/orders/transactions/modify/message.go index 3c504cc41..85d816a80 100644 --- a/x/orders/transactions/modify/message.go +++ b/x/orders/transactions/modify/message.go @@ -22,6 +22,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/put/message.go b/x/orders/transactions/put/message.go index 273fcc40e..1d93a8626 100644 --- a/x/orders/transactions/put/message.go +++ b/x/orders/transactions/put/message.go @@ -20,6 +20,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/revoke/message.go b/x/orders/transactions/revoke/message.go index 43ff83c67..54917e789 100644 --- a/x/orders/transactions/revoke/message.go +++ b/x/orders/transactions/revoke/message.go @@ -17,6 +17,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err diff --git a/x/orders/transactions/take/message.go b/x/orders/transactions/take/message.go index 1b01f0529..f53e53c5b 100644 --- a/x/orders/transactions/take/message.go +++ b/x/orders/transactions/take/message.go @@ -18,6 +18,13 @@ import ( var _ helpers.Message = (*Message)(nil) func (message *Message) Type() string { return Transaction.GetName() } +func (message *Message) GetFromAddress() sdkTypes.AccAddress { + from, err := sdkTypes.AccAddressFromBech32(message.From) + if err != nil { + panic(err) + } + return from +} func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { return err From 6bf2be8a69d4dc1db62f1a044ec3dff296882254 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 18 Mar 2024 17:11:26 +0530 Subject: [PATCH 13/57] feat(transaction_keeper): using getFromAddress method --- .../transactions/define/transaction_keeper.go | 12 +++--------- .../transactions/deputize/transaction_keeper.go | 8 +------- x/assets/transactions/mint/transaction_keeper.go | 5 +---- .../transactions/mutate/transaction_keeper.go | 16 +++++----------- .../renumerate/transaction_keeper.go | 15 +++++---------- .../transactions/revoke/transaction_keeper.go | 8 +------- x/assets/transactions/send/transaction_keeper.go | 6 +----- .../transactions/unwrap/transaction_keeper.go | 5 +---- x/assets/transactions/wrap/transaction_keeper.go | 5 +---- .../transactions/deputize/transaction_keeper.go | 9 ++------- .../transactions/provision/transaction_keeper.go | 5 +---- .../transactions/quash/transaction_keeper.go | 5 +---- .../transactions/revoke/transaction_keeper.go | 9 ++------- .../unprovision/transaction_keeper.go | 6 +----- .../transactions/update/transaction_keeper.go | 15 +++++---------- .../transactions/cancel/transaction_keeper.go | 10 ++-------- .../transactions/deputize/transaction_keeper.go | 8 +------- .../transactions/immediate/transaction_keeper.go | 6 +----- x/orders/transactions/make/transaction_keeper.go | 5 +---- .../transactions/modify/transaction_keeper.go | 6 +----- x/orders/transactions/put/transaction_keeper.go | 5 +---- 21 files changed, 38 insertions(+), 131 deletions(-) diff --git a/x/assets/transactions/define/transaction_keeper.go b/x/assets/transactions/define/transaction_keeper.go index 4636a1125..c79adc047 100644 --- a/x/assets/transactions/define/transaction_keeper.go +++ b/x/assets/transactions/define/transaction_keeper.go @@ -6,15 +6,13 @@ package define import ( "context" - baseLists "github.com/AssetMantle/schema/go/lists/base" - "github.com/AssetMantle/schema/go/qualified/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/utilities" "github.com/AssetMantle/modules/x/classifications/auxiliaries/define" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/super" + baseLists "github.com/AssetMantle/schema/go/lists/base" + "github.com/AssetMantle/schema/go/qualified/base" ) type transactionKeeper struct { @@ -31,11 +29,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/deputize/transaction_keeper.go b/x/assets/transactions/deputize/transaction_keeper.go index fc87b25e3..fa59c26be 100644 --- a/x/assets/transactions/deputize/transaction_keeper.go +++ b/x/assets/transactions/deputize/transaction_keeper.go @@ -6,8 +6,6 @@ package deputize import ( "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/utilities" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" @@ -28,11 +26,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/mint/transaction_keeper.go b/x/assets/transactions/mint/transaction_keeper.go index 09da06d58..8b7dd2027 100644 --- a/x/assets/transactions/mint/transaction_keeper.go +++ b/x/assets/transactions/mint/transaction_keeper.go @@ -53,10 +53,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, err } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/mutate/transaction_keeper.go b/x/assets/transactions/mutate/transaction_keeper.go index 6c6284e46..6a94671e0 100644 --- a/x/assets/transactions/mutate/transaction_keeper.go +++ b/x/assets/transactions/mutate/transaction_keeper.go @@ -6,12 +6,6 @@ package mutate import ( "context" - "github.com/AssetMantle/schema/go/documents/base" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/mappable" @@ -19,6 +13,10 @@ import ( "github.com/AssetMantle/modules/x/classifications/auxiliaries/conform" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/schema/go/documents/base" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + baseLists "github.com/AssetMantle/schema/go/lists/base" + baseQualified "github.com/AssetMantle/schema/go/qualified/base" ) type transactionKeeper struct { @@ -35,11 +33,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/renumerate/transaction_keeper.go b/x/assets/transactions/renumerate/transaction_keeper.go index 2f002dbc5..55b953eab 100644 --- a/x/assets/transactions/renumerate/transaction_keeper.go +++ b/x/assets/transactions/renumerate/transaction_keeper.go @@ -6,12 +6,6 @@ package renumerate import ( "context" - "github.com/AssetMantle/schema/go/data" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - "github.com/AssetMantle/schema/go/properties" - propertyConstants "github.com/AssetMantle/schema/go/properties/constants" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/key" @@ -21,6 +15,10 @@ import ( "github.com/AssetMantle/modules/x/metas/auxiliaries/supplement" "github.com/AssetMantle/modules/x/splits/auxiliaries/mint" "github.com/AssetMantle/modules/x/splits/auxiliaries/renumerate" + "github.com/AssetMantle/schema/go/data" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "github.com/AssetMantle/schema/go/properties" + propertyConstants "github.com/AssetMantle/schema/go/properties/constants" ) type transactionKeeper struct { @@ -43,10 +41,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, errorConstants.NotAuthorized.Wrapf("renumerate is not enabled") } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/revoke/transaction_keeper.go b/x/assets/transactions/revoke/transaction_keeper.go index d316ecaa2..318da9a39 100644 --- a/x/assets/transactions/revoke/transaction_keeper.go +++ b/x/assets/transactions/revoke/transaction_keeper.go @@ -6,8 +6,6 @@ package revoke import ( "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/revoke" @@ -27,11 +25,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/send/transaction_keeper.go b/x/assets/transactions/send/transaction_keeper.go index 042b77062..685a2383f 100644 --- a/x/assets/transactions/send/transaction_keeper.go +++ b/x/assets/transactions/send/transaction_keeper.go @@ -36,11 +36,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/unwrap/transaction_keeper.go b/x/assets/transactions/unwrap/transaction_keeper.go index 4f9db61e8..e102b26bd 100644 --- a/x/assets/transactions/unwrap/transaction_keeper.go +++ b/x/assets/transactions/unwrap/transaction_keeper.go @@ -35,10 +35,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/assets/transactions/wrap/transaction_keeper.go b/x/assets/transactions/wrap/transaction_keeper.go index a0276051c..3c61c1483 100644 --- a/x/assets/transactions/wrap/transaction_keeper.go +++ b/x/assets/transactions/wrap/transaction_keeper.go @@ -36,10 +36,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/identities/transactions/deputize/transaction_keeper.go b/x/identities/transactions/deputize/transaction_keeper.go index 24b746a95..f18c9c311 100644 --- a/x/identities/transactions/deputize/transaction_keeper.go +++ b/x/identities/transactions/deputize/transaction_keeper.go @@ -6,14 +6,12 @@ package deputize import ( "context" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/identities/key" "github.com/AssetMantle/modules/x/identities/mappable" "github.com/AssetMantle/modules/x/identities/utilities" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/deputize" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" ) type transactionKeeper struct { @@ -29,10 +27,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if Mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.FromID)).GetMappable(key.NewKey(message.FromID)); Mappable == nil { return nil, errorConstants.EntityNotFound.Wrapf("identity with ID %s not found", message.FromID.AsString()) diff --git a/x/identities/transactions/provision/transaction_keeper.go b/x/identities/transactions/provision/transaction_keeper.go index 2e452ab49..f5dc36caf 100644 --- a/x/identities/transactions/provision/transaction_keeper.go +++ b/x/identities/transactions/provision/transaction_keeper.go @@ -43,10 +43,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, errorConstants.NotAuthorized.Wrapf("identity with ID %s has reached the maximum allowed number of provision-able addresses %d", message.IdentityID.AsString(), transactionKeeper.parameterManager.Fetch(context).GetParameter(constants.MaxProvisionAddressCountProperty.GetID()).GetMetaProperty().GetData().Get().(data.NumberData).Get()) } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() toAddress, err := sdkTypes.AccAddressFromBech32(message.To) if err != nil { diff --git a/x/identities/transactions/quash/transaction_keeper.go b/x/identities/transactions/quash/transaction_keeper.go index 2d2f33818..e62ca90d8 100644 --- a/x/identities/transactions/quash/transaction_keeper.go +++ b/x/identities/transactions/quash/transaction_keeper.go @@ -42,10 +42,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, errorConstants.NotAuthorized.Wrapf("identity quashing is not enabled") } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if Mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.FromID)).GetMappable(key.NewKey(message.FromID)); Mappable == nil { return nil, errorConstants.EntityNotFound.Wrapf("identity with ID %s not found", message.FromID.AsString()) diff --git a/x/identities/transactions/revoke/transaction_keeper.go b/x/identities/transactions/revoke/transaction_keeper.go index 4d9fb9dbb..be1a6dd50 100644 --- a/x/identities/transactions/revoke/transaction_keeper.go +++ b/x/identities/transactions/revoke/transaction_keeper.go @@ -6,13 +6,11 @@ package revoke import ( "context" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/identities/key" "github.com/AssetMantle/modules/x/identities/mappable" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/revoke" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" ) type transactionKeeper struct { @@ -28,10 +26,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if Mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.FromID)).GetMappable(key.NewKey(message.FromID)); Mappable == nil { return nil, errorConstants.EntityNotFound.Wrapf("identity with ID %s not found", message.FromID.AsString()) diff --git a/x/identities/transactions/unprovision/transaction_keeper.go b/x/identities/transactions/unprovision/transaction_keeper.go index 989fef759..324c01acc 100644 --- a/x/identities/transactions/unprovision/transaction_keeper.go +++ b/x/identities/transactions/unprovision/transaction_keeper.go @@ -28,7 +28,6 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - identityID := message.IdentityID identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(identityID)) @@ -38,10 +37,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa } identity := mappable.GetIdentity(Mappable) - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() toAddress, err := sdkTypes.AccAddressFromBech32(message.To) if err != nil { diff --git a/x/identities/transactions/update/transaction_keeper.go b/x/identities/transactions/update/transaction_keeper.go index b66790a80..0d2cc704a 100644 --- a/x/identities/transactions/update/transaction_keeper.go +++ b/x/identities/transactions/update/transaction_keeper.go @@ -6,18 +6,16 @@ package update import ( "context" - "github.com/AssetMantle/schema/go/documents/base" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/classifications/auxiliaries/member" "github.com/AssetMantle/modules/x/identities/key" "github.com/AssetMantle/modules/x/identities/mappable" "github.com/AssetMantle/modules/x/identities/record" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/schema/go/documents/base" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + baseLists "github.com/AssetMantle/schema/go/lists/base" + baseQualified "github.com/AssetMantle/schema/go/qualified/base" ) type transactionKeeper struct { @@ -33,10 +31,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if Mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.FromID)).GetMappable(key.NewKey(message.FromID)); Mappable == nil { return nil, errorConstants.EntityNotFound.Wrapf("identity with ID %s not found", message.FromID.AsString()) diff --git a/x/orders/transactions/cancel/transaction_keeper.go b/x/orders/transactions/cancel/transaction_keeper.go index a9036728f..b9f5efb73 100644 --- a/x/orders/transactions/cancel/transaction_keeper.go +++ b/x/orders/transactions/cancel/transaction_keeper.go @@ -6,9 +6,6 @@ package cancel import ( "context" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/classifications/auxiliaries/unbond" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" @@ -19,6 +16,7 @@ import ( "github.com/AssetMantle/modules/x/orders/mappable" "github.com/AssetMantle/modules/x/orders/record" "github.com/AssetMantle/modules/x/splits/auxiliaries/transfer" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" ) type transactionKeeper struct { @@ -38,11 +36,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/orders/transactions/deputize/transaction_keeper.go b/x/orders/transactions/deputize/transaction_keeper.go index 9545d2ae5..4ec96e902 100644 --- a/x/orders/transactions/deputize/transaction_keeper.go +++ b/x/orders/transactions/deputize/transaction_keeper.go @@ -6,8 +6,6 @@ package deputize import ( "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/maintainers/auxiliaries/deputize" @@ -28,11 +26,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/orders/transactions/immediate/transaction_keeper.go b/x/orders/transactions/immediate/transaction_keeper.go index 5ea1a22f1..c6a7e3d31 100644 --- a/x/orders/transactions/immediate/transaction_keeper.go +++ b/x/orders/transactions/immediate/transaction_keeper.go @@ -45,11 +45,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/orders/transactions/make/transaction_keeper.go b/x/orders/transactions/make/transaction_keeper.go index 35b3a1ef7..4c5269780 100644 --- a/x/orders/transactions/make/transaction_keeper.go +++ b/x/orders/transactions/make/transaction_keeper.go @@ -59,10 +59,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa // return nil, err } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/orders/transactions/modify/transaction_keeper.go b/x/orders/transactions/modify/transaction_keeper.go index cc8ee3391..ee653374f 100644 --- a/x/orders/transactions/modify/transaction_keeper.go +++ b/x/orders/transactions/modify/transaction_keeper.go @@ -42,11 +42,7 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err diff --git a/x/orders/transactions/put/transaction_keeper.go b/x/orders/transactions/put/transaction_keeper.go index b8ac864aa..5b9c4bed9 100644 --- a/x/orders/transactions/put/transaction_keeper.go +++ b/x/orders/transactions/put/transaction_keeper.go @@ -41,10 +41,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, errorConstants.NotAuthorized.Wrapf("put orders not enabled") } - fromAddress, err := sdkTypes.AccAddressFromBech32(message.From) - if err != nil { - panic("Could not get from address from Bech32 string") - } + fromAddress := message.GetFromAddress() if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { return nil, err From 9411e315253d6e7c0b6946e3e0b70171b365a2f9 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 19 Mar 2024 21:05:52 +0530 Subject: [PATCH 14/57] fix(transaction_keeper_test):Update import paths and enhance helper functions in transaction_keeper_test.go The changes involve updating import paths to retrieve necessary modules like orders, identities, metas, classifications, and dependencies like cosmos-sdk or IBC modules from github. The transaction_keeper test has major enhancements which mainly revolve around creating a more comprehensive test setup as well as updating the parameters for wrapping transactions. --- .../wrap/transaction_keeper_test.go | 248 +++++++++++++----- 1 file changed, 178 insertions(+), 70 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper_test.go b/x/assets/transactions/wrap/transaction_keeper_test.go index 5f5c3ba8c..f7756b521 100644 --- a/x/assets/transactions/wrap/transaction_keeper_test.go +++ b/x/assets/transactions/wrap/transaction_keeper_test.go @@ -6,44 +6,112 @@ package wrap import ( "context" "fmt" - "github.com/AssetMantle/modules/x/splits/record" + "github.com/AssetMantle/modules/helpers" + baseHelpers "github.com/AssetMantle/modules/helpers/base" + "github.com/AssetMantle/modules/x/assets/mapper" + "github.com/AssetMantle/modules/x/assets/parameters" + "github.com/AssetMantle/modules/x/assets/record" + "github.com/AssetMantle/modules/x/classifications" + "github.com/AssetMantle/modules/x/identities" + "github.com/AssetMantle/modules/x/maintainers" + "github.com/AssetMantle/modules/x/metas" + "github.com/AssetMantle/modules/x/orders" + "github.com/AssetMantle/modules/x/splits" + "github.com/AssetMantle/modules/x/splits/constants" baseData "github.com/AssetMantle/schema/go/data/base" baseDocuments "github.com/AssetMantle/schema/go/documents/base" baseIDs "github.com/AssetMantle/schema/go/ids/base" baseLists "github.com/AssetMantle/schema/go/lists/base" + "github.com/AssetMantle/schema/go/parameters/base" baseProperties "github.com/AssetMantle/schema/go/properties/base" + constantProperties "github.com/AssetMantle/schema/go/properties/constants" baseQualified "github.com/AssetMantle/schema/go/qualified/base" - "reflect" - "testing" - - baseTypes "github.com/AssetMantle/schema/go/types/base" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/keeper" authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + authzModule "github.com/cosmos/cosmos-sdk/x/authz/module" + "github.com/cosmos/cosmos-sdk/x/bank" bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/capability" + "github.com/cosmos/cosmos-sdk/x/crisis" + "github.com/cosmos/cosmos-sdk/x/distribution" + distributionClient "github.com/cosmos/cosmos-sdk/x/distribution/client" + distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/evidence" + feegrantModule "github.com/cosmos/cosmos-sdk/x/feegrant/module" + "github.com/cosmos/cosmos-sdk/x/genutil" + "github.com/cosmos/cosmos-sdk/x/gov" + govTypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/mint" + mintTypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/params" + paramsClient "github.com/cosmos/cosmos-sdk/x/params/client" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradeClient "github.com/cosmos/cosmos-sdk/x/upgrade/client" + ica "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts" + icaTypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/types" + "github.com/cosmos/ibc-go/v4/modules/apps/transfer" + ibcTransferTypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" + ibc "github.com/cosmos/ibc-go/v4/modules/core" + ibcClientClient "github.com/cosmos/ibc-go/v4/modules/core/02-client/client" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" - - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/assets/mapper" - "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" - "github.com/AssetMantle/modules/x/splits/constants" - "github.com/AssetMantle/modules/x/splits/parameters" + "reflect" + "testing" ) +type MockAuxiliary struct { + mock.Mock +} + +func (m *MockAuxiliary) GetName() string { + //TODO implement me + panic("implement me") +} + +func (m *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := m.Called() + return args.Get(0).(helpers.AuxiliaryKeeper) +} + +func (m *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + //TODO implement me + panic("implement me") +} + +type MockAuxiliaryKeeper struct { + mock.Mock +} + +var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) + +func (m *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := m.Called(context, request) + return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) +} + +func (m *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := m.Called(m2, manager, i) + return args.Get(0).(helpers.Keeper) +} + var ( authenticateAuxiliary helpers.Auxiliary mintAuxiliary helpers.Auxiliary @@ -51,31 +119,60 @@ var ( delAddr1 = sdkTypes.AccAddress(delPk1.Address()) ) -type TestKeepers struct { - WrapKeeper helpers.TransactionKeeper -} - -func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.ParameterManager, bankKeeper.Keeper) { +func createTestInput(t *testing.T) (sdkTypes.Context, helpers.TransactionKeeper, helpers.Mapper, helpers.ParameterManager, bankKeeper.Keeper) { var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() + var ModuleBasicManager = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.AppModuleBasic{}, + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distribution.AppModuleBasic{}, + gov.NewAppModuleBasic( + paramsClient.ProposalHandler, + distributionClient.ProposalHandler, + upgradeClient.ProposalHandler, + upgradeClient.CancelProposalHandler, + ibcClientClient.UpdateClientProposalHandler, + ibcClientClient.UpgradeProposalHandler, + ), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + feegrantModule.AppModuleBasic{}, + authzModule.AppModuleBasic{}, + ibc.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, + vesting.AppModuleBasic{}, + ica.AppModuleBasic{}, + + classifications.Prototype(), + identities.Prototype(), + maintainers.Prototype(), + metas.Prototype(), + orders.Prototype(), + splits.Prototype(), + ) - Codec := baseHelpers.CodecPrototype() + Codec := baseHelpers.CodecPrototype().Initialize(ModuleBasicManager) storeKey := sdkTypes.NewKVStoreKey("test") keyAcc := sdkTypes.NewKVStoreKey(authTypes.StoreKey) - keyDistr := sdkTypes.NewKVStoreKey(types.StoreKey) + keyDistr := sdkTypes.NewKVStoreKey(distributionTypes.StoreKey) keyStaking := sdkTypes.NewKVStoreKey(stakingTypes.StoreKey) paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") Mapper := mapper.Prototype().Initialize(storeKey) encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, + encodingConfig.Marshaler, legacyAmino, paramsStoreKey, paramsTransientStoreKeys, ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) @@ -88,27 +185,67 @@ func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mappe err := commitMultiStore.LoadLatestVersion() require.Nil(t, err) - authenticateAuxiliary = authenticate.Auxiliary.Initialize(Mapper, parameterManager) + authenticateAuxiliaryKeeper := new(MockAuxiliaryKeeper) + authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + authenticateAuxiliary = new(MockAuxiliary) + authenticateAuxiliary.(*MockAuxiliary).On("GetKeeper").Return(authenticateAuxiliaryKeeper) + + mintAuxiliaryKeeper := new(MockAuxiliaryKeeper) + mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + mintAuxiliary = new(MockAuxiliary) + mintAuxiliary.(*MockAuxiliary).On("GetKeeper").Return(mintAuxiliaryKeeper) Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) + parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test").WithKeyTable(parameters.Prototype().GetKeyTable())) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) + feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(types.ModuleName) + distrAcc := authTypes.NewEmptyModuleAccount(distributionTypes.ModuleName) splitAcc := authTypes.NewEmptyModuleAccount(constants.ModuleName) - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true - blacklistedAddrs[notBondedPool.GetAddress().String()] = true - blacklistedAddrs[bondPool.GetAddress().String()] = true - blacklistedAddrs[distrAcc.GetAddress().String()] = true - blacklistedAddrs[splitAcc.GetAddress().String()] = true + var ModuleAccountPermissions = map[string][]string{ + authTypes.FeeCollectorName: nil, + distributionTypes.ModuleName: nil, + icaTypes.ModuleName: nil, + mintTypes.ModuleName: {authTypes.Minter}, + stakingTypes.BondedPoolName: {authTypes.Burner, authTypes.Staking}, + stakingTypes.NotBondedPoolName: {authTypes.Burner, authTypes.Staking}, + govTypes.ModuleName: {authTypes.Burner}, + ibcTransferTypes.ModuleName: {authTypes.Minter, authTypes.Burner}, + "test": {authTypes.Minter}, + "assets": nil, + classifications.Prototype().Name(): {authTypes.Burner}, + } + + var TokenReceiveAllowedModules = map[string]bool{ + distributionTypes.ModuleName: true, + } + + blacklistedAddresses := make(map[string]bool) + for account := range ModuleAccountPermissions { + blacklistedAddresses[authTypes.NewModuleAddress(account).String()] = !TokenReceiveAllowedModules[account] + } - accountKeeper := keeper.NewAccountKeeper(Codec.GetProtoCodec(), keyAcc, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, nil) - BankKeeper := bankKeeper.NewBaseKeeper(Codec.GetProtoCodec(), keyAcc, accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddrs) + accountKeeper := keeper.NewAccountKeeper(Codec.GetProtoCodec(), keyAcc, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, ModuleAccountPermissions) + BankKeeper := bankKeeper.NewBaseKeeper(Codec.GetProtoCodec(), keyAcc, accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddresses) + + testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(1000000000000))) + if err := BankKeeper.MintCoins(Context, "test", testCoins); err != nil { + panic(err) + } + + if err := BankKeeper.SendCoinsFromModuleToAccount(Context, "test", delAddr1, testCoins); err != nil { + panic(err) + } sk := stakingKeeper.NewKeeper(Codec.GetProtoCodec(), keyStaking, accountKeeper, BankKeeper, ParamsKeeper.Subspace(stakingTypes.ModuleName)) sk.SetParams(Context, stakingTypes.DefaultParams()) @@ -123,11 +260,9 @@ func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mappe accountKeeper.SetModuleAccount(Context, distrAcc) accountKeeper.SetModuleAccount(Context, splitAcc) - keepers := TestKeepers{ - WrapKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.TransactionKeeper), - } + wrapKeeper := keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.TransactionKeeper) - return Context, keepers, Mapper, parameterManager, BankKeeper + return Context, wrapKeeper, Mapper, parameterManager, BankKeeper } func Test_keeperPrototype(t *testing.T) { @@ -168,7 +303,7 @@ func Test_transactionKeeper_Initialize(t *testing.T) { feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(types.ModuleName) + distrAcc := authTypes.NewEmptyModuleAccount(distributionTypes.ModuleName) blacklistedAddrs := make(map[string]bool) blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true blacklistedAddrs[notBondedPool.GetAddress().String()] = true @@ -212,41 +347,14 @@ func Test_transactionKeeper_Initialize(t *testing.T) { } func Test_transactionKeeper_Transact(t *testing.T) { - Context, keepers, Mapper, parameterManager, _ := createTestInput(t) + Context, wrapKeepers, Mapper, parameterManager, BankKeeper := createTestInput(t) immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) classificationID := baseIDs.NewClassificationID(immutables, mutables) - testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) - testRate1 := sdkTypes.NewCoins(sdkTypes.NewInt64Coin("stake", 1)) - testAssetID := baseDocuments.NewCoinAsset("stake").GetCoinAssetID() - split := baseTypes.NewSplit(sdkTypes.NewInt(1)) - keepers.WrapKeeper.(transactionKeeper).mapper.NewCollection(Context.Context()).Add(record.NewRecord(baseIDs.NewSplitID(testAssetID, testOwnerIdentityID), split)) - feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) - notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) - bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(types.ModuleName) - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true - blacklistedAddrs[notBondedPool.GetAddress().String()] = true - blacklistedAddrs[bondPool.GetAddress().String()] = true - blacklistedAddrs[distrAcc.GetAddress().String()] = true - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + testAsset := baseDocuments.NewAsset(classificationID, immutables, mutables) + testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.OneInt())) - ParamsKeeper := paramsKeeper.NewKeeper( - baseHelpers.CodecPrototype(), - codec.NewLegacyAmino(), - paramsStoreKey, - paramsTransientStoreKeys, - ) - accountKeeper := authKeeper.NewAccountKeeper( - codec.NewProtoCodec(nil), - sdkTypes.NewKVStoreKey(authTypes.StoreKey), - ParamsKeeper.Subspace(authTypes.ModuleName), - authTypes.ProtoBaseAccount, - nil, - ) - BankKeeper := bankKeeper.NewBaseKeeper(baseHelpers.CodecPrototype().GetProtoCodec(), sdkTypes.NewKVStoreKey(bankTypes.StoreKey), accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddrs) + wrapKeepers.(transactionKeeper).mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(testAsset)) type fields struct { mapper helpers.Mapper @@ -266,7 +374,7 @@ func Test_transactionKeeper_Transact(t *testing.T) { want helpers.TransactionResponse wantErr bool }{ - {"+ve", fields{Mapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{Context.Context(), NewMessage(delAddr1, fromID, testRate1)}, newTransactionResponse(), false}, + {"+ve", fields{Mapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{sdkTypes.WrapSDKContext(Context), NewMessage(delAddr1, fromID, testCoins)}, newTransactionResponse(), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From 1244f96570db101bb9113920c3ab26f50b07177f Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 22 Mar 2024 19:46:24 +0530 Subject: [PATCH 15/57] refactor(transaction_keeper_test):optimizing test case --- .../wrap/transaction_keeper_test.go | 295 +++++------------- 1 file changed, 75 insertions(+), 220 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper_test.go b/x/assets/transactions/wrap/transaction_keeper_test.go index f7756b521..b4db926b8 100644 --- a/x/assets/transactions/wrap/transaction_keeper_test.go +++ b/x/assets/transactions/wrap/transaction_keeper_test.go @@ -7,68 +7,27 @@ import ( "context" "fmt" "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" + "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/mapper" "github.com/AssetMantle/modules/x/assets/parameters" - "github.com/AssetMantle/modules/x/assets/record" - "github.com/AssetMantle/modules/x/classifications" - "github.com/AssetMantle/modules/x/identities" - "github.com/AssetMantle/modules/x/maintainers" - "github.com/AssetMantle/modules/x/metas" - "github.com/AssetMantle/modules/x/orders" - "github.com/AssetMantle/modules/x/splits" - "github.com/AssetMantle/modules/x/splits/constants" baseData "github.com/AssetMantle/schema/go/data/base" - baseDocuments "github.com/AssetMantle/schema/go/documents/base" - baseIDs "github.com/AssetMantle/schema/go/ids/base" baseLists "github.com/AssetMantle/schema/go/lists/base" "github.com/AssetMantle/schema/go/parameters/base" baseProperties "github.com/AssetMantle/schema/go/properties/base" constantProperties "github.com/AssetMantle/schema/go/properties/constants" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/keeper" authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - authzModule "github.com/cosmos/cosmos-sdk/x/authz/module" - "github.com/cosmos/cosmos-sdk/x/bank" bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/distribution" - distributionClient "github.com/cosmos/cosmos-sdk/x/distribution/client" distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/evidence" - feegrantModule "github.com/cosmos/cosmos-sdk/x/feegrant/module" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/gov" - govTypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/mint" - mintTypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/params" - paramsClient "github.com/cosmos/cosmos-sdk/x/params/client" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeClient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - ica "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts" - icaTypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/types" - "github.com/cosmos/ibc-go/v4/modules/apps/transfer" - ibcTransferTypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v4/modules/core" - ibcClientClient "github.com/cosmos/ibc-go/v4/modules/core/02-client/client" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" @@ -81,19 +40,15 @@ type MockAuxiliary struct { mock.Mock } -func (m *MockAuxiliary) GetName() string { - //TODO implement me - panic("implement me") -} +var _ helpers.Auxiliary = (*MockAuxiliary)(nil) -func (m *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { - args := m.Called() +func (mockAuxiliary *MockAuxiliary) GetName() string { panic(mockAuxiliary) } +func (mockAuxiliary *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := mockAuxiliary.Called() return args.Get(0).(helpers.AuxiliaryKeeper) } - -func (m *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { - //TODO implement me - panic("implement me") +func (mockAuxiliary *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + panic(mockAuxiliary) } type MockAuxiliaryKeeper struct { @@ -102,167 +57,82 @@ type MockAuxiliaryKeeper struct { var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) -func (m *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { - args := m.Called(context, request) +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := mockAuxiliaryKeeper.Called(context, request) return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) } - -func (m *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { - args := m.Called(m2, manager, i) +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := mockAuxiliaryKeeper.Called(m2, manager, i) return args.Get(0).(helpers.Keeper) } var ( - authenticateAuxiliary helpers.Auxiliary - mintAuxiliary helpers.Auxiliary - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdkTypes.AccAddress(delPk1.Address()) -) + encodingConfig = simapp.MakeTestEncodingConfig() -func createTestInput(t *testing.T) (sdkTypes.Context, helpers.TransactionKeeper, helpers.Mapper, helpers.ParameterManager, bankKeeper.Keeper) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - var ModuleBasicManager = module.NewBasicManager( - auth.AppModuleBasic{}, - genutil.AppModuleBasic{}, - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - gov.NewAppModuleBasic( - paramsClient.ProposalHandler, - distributionClient.ProposalHandler, - upgradeClient.ProposalHandler, - upgradeClient.CancelProposalHandler, - ibcClientClient.UpdateClientProposalHandler, - ibcClientClient.UpgradeProposalHandler, - ), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - feegrantModule.AppModuleBasic{}, - authzModule.AppModuleBasic{}, - ibc.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, - ica.AppModuleBasic{}, + authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) + mintAuxiliaryKeeper = new(MockAuxiliaryKeeper) + authenticateAuxiliary = new(MockAuxiliary) + mintAuxiliary = new(MockAuxiliary) + moduleStoreKey = sdkTypes.NewKVStoreKey(moduleName) - classifications.Prototype(), - identities.Prototype(), - maintainers.Prototype(), - metas.Prototype(), - orders.Prototype(), - splits.Prototype(), - ) + authStoreKey = sdkTypes.NewKVStoreKey(authTypes.StoreKey) + bankStoreKey = sdkTypes.NewKVStoreKey(bankTypes.StoreKey) + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) - Codec := baseHelpers.CodecPrototype().Initialize(ModuleBasicManager) + genesisCoinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.NewInt(1000000000000))) + genesisAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + moduleName = constants.ModuleName - storeKey := sdkTypes.NewKVStoreKey("test") - keyAcc := sdkTypes.NewKVStoreKey(authTypes.StoreKey) - keyDistr := sdkTypes.NewKVStoreKey(distributionTypes.StoreKey) - keyStaking := sdkTypes.NewKVStoreKey(stakingTypes.StoreKey) - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - ParamsKeeper := paramsKeeper.NewKeeper( - encodingConfig.Marshaler, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(keyDistr, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(keyStaking, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(keyAcc, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) + moduleAccountPermissions = map[string][]string{TestMinterModuleName: {authTypes.Minter}, moduleName: nil} + AuthKeeper = authKeeper.NewAccountKeeper(encodingConfig.Marshaler, authStoreKey, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, moduleAccountPermissions) - authenticateAuxiliaryKeeper := new(MockAuxiliaryKeeper) - authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - authenticateAuxiliary = new(MockAuxiliary) - authenticateAuxiliary.(*MockAuxiliary).On("GetKeeper").Return(authenticateAuxiliaryKeeper) + blacklistedAddresses = map[string]bool{authTypes.NewModuleAddress(TestMinterModuleName).String(): false, authTypes.NewModuleAddress(moduleName).String(): false} + BankKeeper = bankKeeper.NewBaseKeeper(encodingConfig.Marshaler, bankStoreKey, AuthKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddresses) - mintAuxiliaryKeeper := new(MockAuxiliaryKeeper) - mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - mintAuxiliary = new(MockAuxiliary) - mintAuxiliary.(*MockAuxiliary).On("GetKeeper").Return(mintAuxiliaryKeeper) + Context = setContext() + + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, genesisCoinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, genesisCoinSupply) + + parameterManager = setParameterManager(Context, ParamsKeeper) - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) + moduleMapper = mapper.Prototype().Initialize(moduleStoreKey) +) + +const ( + TestMinterModuleName = "testMinter" + Denom = "stake" + ChainID = "testChain" +) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test").WithKeyTable(parameters.Prototype().GetKeyTable())) +func setMockBehaviour() { + authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) + mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + mintAuxiliary.On("GetKeeper").Return(mintAuxiliaryKeeper) +} +func setParameterManager(Context sdkTypes.Context, ParamsKeeper paramsKeeper.Keeper) helpers.ParameterManager { + parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace(moduleName).WithKeyTable(parameters.Prototype().GetKeyTable())) parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) - - feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) - notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) - bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(distributionTypes.ModuleName) - splitAcc := authTypes.NewEmptyModuleAccount(constants.ModuleName) - - var ModuleAccountPermissions = map[string][]string{ - authTypes.FeeCollectorName: nil, - distributionTypes.ModuleName: nil, - icaTypes.ModuleName: nil, - mintTypes.ModuleName: {authTypes.Minter}, - stakingTypes.BondedPoolName: {authTypes.Burner, authTypes.Staking}, - stakingTypes.NotBondedPoolName: {authTypes.Burner, authTypes.Staking}, - govTypes.ModuleName: {authTypes.Burner}, - ibcTransferTypes.ModuleName: {authTypes.Minter, authTypes.Burner}, - "test": {authTypes.Minter}, - "assets": nil, - classifications.Prototype().Name(): {authTypes.Burner}, - } - - var TokenReceiveAllowedModules = map[string]bool{ - distributionTypes.ModuleName: true, - } - - blacklistedAddresses := make(map[string]bool) - for account := range ModuleAccountPermissions { - blacklistedAddresses[authTypes.NewModuleAddress(account).String()] = !TokenReceiveAllowedModules[account] - } - - accountKeeper := keeper.NewAccountKeeper(Codec.GetProtoCodec(), keyAcc, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, ModuleAccountPermissions) - BankKeeper := bankKeeper.NewBaseKeeper(Codec.GetProtoCodec(), keyAcc, accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddresses) - - testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(1000000000000))) - if err := BankKeeper.MintCoins(Context, "test", testCoins); err != nil { - panic(err) - } - - if err := BankKeeper.SendCoinsFromModuleToAccount(Context, "test", delAddr1, testCoins); err != nil { - panic(err) - } - - sk := stakingKeeper.NewKeeper(Codec.GetProtoCodec(), keyStaking, accountKeeper, BankKeeper, ParamsKeeper.Subspace(stakingTypes.ModuleName)) - sk.SetParams(Context, stakingTypes.DefaultParams()) - //intToken := sdkTypes.TokensFromConsensusPower(1000000, sdkTypes.NewInt(100)) - //initCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(Context), intToken)) - //totalSupply := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(Context), intToken.MulRaw(int64(len(TestAddrs))))) - - // set module accounts - accountKeeper.SetModuleAccount(Context, feeCollectorAcc) - accountKeeper.SetModuleAccount(Context, notBondedPool) - accountKeeper.SetModuleAccount(Context, bondPool) - accountKeeper.SetModuleAccount(Context, distrAcc) - accountKeeper.SetModuleAccount(Context, splitAcc) - - wrapKeeper := keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.TransactionKeeper) - - return Context, wrapKeeper, Mapper, parameterManager, BankKeeper + return parameterManager +} +func setContext() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(authStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(bankStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) } func Test_keeperPrototype(t *testing.T) { @@ -282,7 +152,7 @@ func Test_keeperPrototype(t *testing.T) { } func Test_transactionKeeper_Initialize(t *testing.T) { - _, _, Mapper, parameterManager, _ := createTestInput(t) + setMockBehaviour() paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") encodingConfig := simapp.MakeTestEncodingConfig() @@ -328,7 +198,7 @@ func Test_transactionKeeper_Initialize(t *testing.T) { args args want helpers.Keeper }{ - {"+ve", fields{Mapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{Mapper, parameterManager, []interface{}{}}, transactionKeeper{Mapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}}, + {"+ve", fields{moduleMapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{moduleMapper, parameterManager, []interface{}{}}, transactionKeeper{moduleMapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -347,45 +217,30 @@ func Test_transactionKeeper_Initialize(t *testing.T) { } func Test_transactionKeeper_Transact(t *testing.T) { - Context, wrapKeepers, Mapper, parameterManager, BankKeeper := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - testAsset := baseDocuments.NewAsset(classificationID, immutables, mutables) - testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.OneInt())) - - wrapKeepers.(transactionKeeper).mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(testAsset)) + setMockBehaviour() + testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.OneInt())) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - bankKeeper bankKeeper.Keeper - authenticateAuxiliary helpers.Auxiliary - mintAuxiliary helpers.Auxiliary - } type args struct { - context context.Context message sdkTypes.Msg } tests := []struct { name string - fields fields args args want helpers.TransactionResponse wantErr bool }{ - {"+ve", fields{Mapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{sdkTypes.WrapSDKContext(Context), NewMessage(delAddr1, fromID, testCoins)}, newTransactionResponse(), false}, + {"+ve", args{NewMessage(genesisAddress, fromID, testCoins)}, newTransactionResponse(), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - bankKeeper: tt.fields.bankKeeper, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, - mintAuxiliary: tt.fields.mintAuxiliary, + moduleMapper, + parameterManager, + BankKeeper, + authenticateAuxiliary, + mintAuxiliary, } - got, err := transactionKeeper.Transact(tt.args.context, tt.args.message.(helpers.Message)) + got, err := transactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), tt.args.message.(helpers.Message)) if (err != nil) != tt.wantErr { t.Errorf("Transact() error = %v, wantErr %v", err, tt.wantErr) return From 026086b15f28bc0a55415ef183e77212169318f6 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 25 Mar 2024 21:25:35 +0530 Subject: [PATCH 16/57] refactor(parameter_manager): return self on set. --- helpers/base/parameter_manager.go | 10 ++++++---- helpers/parameter_manager.go | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/helpers/base/parameter_manager.go b/helpers/base/parameter_manager.go index 8e684eeb5..d4843e521 100644 --- a/helpers/base/parameter_manager.go +++ b/helpers/base/parameter_manager.go @@ -30,11 +30,11 @@ type parameterManager struct { var _ helpers.ParameterManager = (*parameterManager)(nil) func (parameterManager parameterManager) Get() lists.ParameterList { - parameters := make([]parameters.Parameter, len(parameterManager.validatableParameters)) + Parameters := make([]parameters.Parameter, len(parameterManager.validatableParameters)) for i, validatableParameter := range parameterManager.validatableParameters { - parameters[i] = validatableParameter.GetParameter() + Parameters[i] = validatableParameter.GetParameter() } - return baseLists.NewParameterList(parameters...) + return baseLists.NewParameterList(Parameters...) } func (parameterManager parameterManager) GetParameter(propertyID ids.PropertyID) parameters.Parameter { if validatableParameter := parameterManager.GetValidatableParameter(propertyID); validatableParameter != nil { @@ -74,10 +74,12 @@ func (parameterManager parameterManager) Fetch(context context.Context) helpers. return parameterManager } -func (parameterManager parameterManager) Set(context context.Context, parameterList lists.ParameterList) { +func (parameterManager parameterManager) Set(context context.Context, parameterList lists.ParameterList) helpers.ParameterManager { for _, parameter := range parameterList.Get() { parameterManager.paramsSubspace.Set(sdkTypes.UnwrapSDKContext(context), parameter.GetMetaProperty().GetID().Bytes(), parameter.GetMetaProperty().GetData().Get().AsString()) } + + return parameterManager } func (parameterManager parameterManager) ParamSetPairs() paramsTypes.ParamSetPairs { paramSetPairList := make([]paramsTypes.ParamSetPair, len(parameterManager.validatableParameters)) diff --git a/helpers/parameter_manager.go b/helpers/parameter_manager.go index 9023a6b31..4c96312d4 100644 --- a/helpers/parameter_manager.go +++ b/helpers/parameter_manager.go @@ -21,7 +21,7 @@ type ParameterManager interface { ValidateParameter(parameters.Parameter) error Fetch(context.Context) ParameterManager - Set(context.Context, lists.ParameterList) + Set(context.Context, lists.ParameterList) ParameterManager GetKeyTable() paramsTypes.KeyTable RESTQueryHandler(client.Context) http.HandlerFunc From b7e6012eb941ee7545ce3424dff03088f2cf5c0e Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 25 Mar 2024 21:27:17 +0530 Subject: [PATCH 17/57] refactor(wrap): performance optimization --- .../transactions/wrap/transaction_keeper.go | 37 +++++++------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper.go b/x/assets/transactions/wrap/transaction_keeper.go index 3c61c1483..cf6bd0d6b 100644 --- a/x/assets/transactions/wrap/transaction_keeper.go +++ b/x/assets/transactions/wrap/transaction_keeper.go @@ -5,20 +5,18 @@ package wrap import ( "context" - - "github.com/AssetMantle/schema/go/data/base" - baseDocuments "github.com/AssetMantle/schema/go/documents/base" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - constantProperties "github.com/AssetMantle/schema/go/properties/constants" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/record" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/splits/auxiliaries/mint" + "github.com/AssetMantle/schema/go/data/base" + baseDocuments "github.com/AssetMantle/schema/go/documents/base" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + constantProperties "github.com/AssetMantle/schema/go/properties/constants" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" ) type transactionKeeper struct { @@ -36,33 +34,24 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress := message.GetFromAddress() - - if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { + if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.GetFromAddress(), message.FromID)); err != nil { return nil, err } - if err := transactionKeeper.bankKeeper.SendCoinsFromAccountToModule(sdkTypes.UnwrapSDKContext(context), fromAddress, constants.ModuleName, message.Coins); err != nil { - return nil, err - } + wrapAllowedCoins := transactionKeeper.parameterManager.Fetch(context).GetParameter(constantProperties.WrapAllowedCoinsProperty.GetID()).GetMetaProperty().GetData().Get().(*base.ListData) for _, coin := range message.Coins { - if err := sdkTypes.ValidateDenom(coin.Denom); err != nil { - return nil, errorConstants.InvalidRequest.Wrapf("coin denom %s is invalid", coin.Denom) + if _, found := wrapAllowedCoins.Search(base.NewStringData(coin.Denom)); !found { + return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be wrapped", coin.Denom) } - if _, found := transactionKeeper.parameterManager.Fetch(context).GetParameter(constantProperties.WrapAllowedCoinsProperty.GetID()).GetMetaProperty().GetData().Get().(*base.ListData).Search(base.NewStringData(coin.Denom)); !found { - return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be wrapped", coin.Denom) + if err := transactionKeeper.bankKeeper.SendCoinsFromAccountToModule(sdkTypes.UnwrapSDKContext(context), message.GetFromAddress(), constants.ModuleName, sdkTypes.NewCoins(coin)); err != nil { + return nil, err } coinAsset := baseDocuments.NewCoinAsset(coin.Denom) - value := coin.Amount - if value.IsNegative() { - return nil, errorConstants.InvalidRequest.Wrapf("coin amount %s is negative", coin.Amount) - } - - if _, err := transactionKeeper.mintAuxiliary.GetKeeper().Help(context, mint.NewAuxiliaryRequest(message.FromID, coinAsset.GetCoinAssetID(), value)); err != nil { + if _, err := transactionKeeper.mintAuxiliary.GetKeeper().Help(context, mint.NewAuxiliaryRequest(message.FromID, coinAsset.GetCoinAssetID(), coin.Amount)); err != nil { return nil, err } From 1e3345c5ba611d49088e01ba971be793d56c37e6 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 25 Mar 2024 21:27:38 +0530 Subject: [PATCH 18/57] test(wrap): code optimization --- .../wrap/transaction_keeper_test.go | 314 ++++++++++-------- 1 file changed, 174 insertions(+), 140 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper_test.go b/x/assets/transactions/wrap/transaction_keeper_test.go index b4db926b8..51be0e912 100644 --- a/x/assets/transactions/wrap/transaction_keeper_test.go +++ b/x/assets/transactions/wrap/transaction_keeper_test.go @@ -5,17 +5,18 @@ package wrap import ( "context" - "fmt" "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/constants" + "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/mapper" "github.com/AssetMantle/modules/x/assets/parameters" baseData "github.com/AssetMantle/schema/go/data/base" + baseDocuments "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/ids" baseLists "github.com/AssetMantle/schema/go/lists/base" "github.com/AssetMantle/schema/go/parameters/base" baseProperties "github.com/AssetMantle/schema/go/properties/base" constantProperties "github.com/AssetMantle/schema/go/properties/constants" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" @@ -23,16 +24,16 @@ import ( authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/mock" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "math/rand" "reflect" + "strconv" "testing" ) @@ -66,63 +67,60 @@ func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, ma return args.Get(0).(helpers.Keeper) } +const ( + TestMinterModuleName = "testMinter" + Denom = "stake" + ChainID = "testChain" + GenesisSupply = 1000000000000 +) + var ( - encodingConfig = simapp.MakeTestEncodingConfig() + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) - mintAuxiliaryKeeper = new(MockAuxiliaryKeeper) - authenticateAuxiliary = new(MockAuxiliary) - mintAuxiliary = new(MockAuxiliary) - moduleStoreKey = sdkTypes.NewKVStoreKey(moduleName) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - authStoreKey = sdkTypes.NewKVStoreKey(authTypes.StoreKey) - bankStoreKey = sdkTypes.NewKVStoreKey(bankTypes.StoreKey) - paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) - paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + mintAuxiliaryKeeper = new(MockAuxiliaryKeeper) + _ = mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - genesisCoinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.NewInt(1000000000000))) - genesisAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) - moduleName = constants.ModuleName + authenticateAuxiliary = new(MockAuxiliary) + _ = authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) - ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) + mintAuxiliary = new(MockAuxiliary) + _ = mintAuxiliary.On("GetKeeper").Return(mintAuxiliaryKeeper) + + encodingConfig = simapp.MakeTestEncodingConfig() + + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) - moduleAccountPermissions = map[string][]string{TestMinterModuleName: {authTypes.Minter}, moduleName: nil} + authStoreKey = sdkTypes.NewKVStoreKey(authTypes.StoreKey) + moduleAccountPermissions = map[string][]string{TestMinterModuleName: {authTypes.Minter}, constants.ModuleName: nil} AuthKeeper = authKeeper.NewAccountKeeper(encodingConfig.Marshaler, authStoreKey, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, moduleAccountPermissions) - blacklistedAddresses = map[string]bool{authTypes.NewModuleAddress(TestMinterModuleName).String(): false, authTypes.NewModuleAddress(moduleName).String(): false} + bankStoreKey = sdkTypes.NewKVStoreKey(bankTypes.StoreKey) + blacklistedAddresses = map[string]bool{authTypes.NewModuleAddress(TestMinterModuleName).String(): false, authTypes.NewModuleAddress(constants.ModuleName).String(): false} BankKeeper = bankKeeper.NewBaseKeeper(encodingConfig.Marshaler, bankStoreKey, AuthKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddresses) Context = setContext() - _ = BankKeeper.MintCoins(Context, TestMinterModuleName, genesisCoinSupply) - _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, genesisCoinSupply) + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) - parameterManager = setParameterManager(Context, ParamsKeeper) + genesisAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) - moduleMapper = mapper.Prototype().Initialize(moduleStoreKey) -) + parameterManager = parameters.Prototype().Initialize(ParamsKeeper.Subspace(constants.ModuleName).WithKeyTable(parameters.Prototype().GetKeyTable())). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))) -const ( - TestMinterModuleName = "testMinter" - Denom = "stake" - ChainID = "testChain" + TransactionKeeper = transactionKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary} ) -func setMockBehaviour() { - authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) - mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - mintAuxiliary.On("GetKeeper").Return(mintAuxiliaryKeeper) -} -func setParameterManager(Context sdkTypes.Context, ParamsKeeper paramsKeeper.Keeper) helpers.ParameterManager { - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace(moduleName).WithKeyTable(parameters.Prototype().GetKeyTable())) - parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) - parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) - parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) - parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))) - parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData("stake")))))) - return parameterManager -} func setContext() sdkTypes.Context { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) @@ -135,118 +133,154 @@ func setContext() sdkTypes.Context { return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) } -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.TransactionKeeper - }{ - {"+ve", transactionKeeper{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) - } - }) - } -} - -func Test_transactionKeeper_Initialize(t *testing.T) { - setMockBehaviour() - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - codec.NewLegacyAmino(), - paramsStoreKey, - paramsTransientStoreKeys, - ) - accountKeeper := authKeeper.NewAccountKeeper( - codec.NewProtoCodec(nil), - sdkTypes.NewKVStoreKey(authTypes.StoreKey), - ParamsKeeper.Subspace(authTypes.ModuleName), - authTypes.ProtoBaseAccount, - nil, - ) - feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) - notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) - bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(distributionTypes.ModuleName) - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true - blacklistedAddrs[notBondedPool.GetAddress().String()] = true - blacklistedAddrs[bondPool.GetAddress().String()] = true - blacklistedAddrs[distrAcc.GetAddress().String()] = true - BankKeeper := bankKeeper.NewBaseKeeper(appCodec, sdkTypes.NewKVStoreKey(bankTypes.StoreKey), accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddrs) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - bankKeeper bankKeeper.Keeper - authenticateAuxiliary helpers.Auxiliary - mintAuxiliary helpers.Auxiliary - } +func TestTransactionKeeperTransact(t *testing.T) { type args struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - auxiliaries []interface{} + from sdkTypes.AccAddress + fromID ids.IdentityID + denom string + amount int } tests := []struct { - name string - fields fields - args args - want helpers.Keeper + name string + args args + setup func() + want *TransactionResponse + wantErr bool }{ - {"+ve", fields{moduleMapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}, args{moduleMapper, parameterManager, []interface{}{}}, transactionKeeper{moduleMapper, parameterManager, BankKeeper, authenticateAuxiliary, mintAuxiliary}}, + {"wrapOne", + args{genesisAddress, fromID, Denom, 1}, + func() {}, + newTransactionResponse(), + false, + }, + {"wrapRandom", + args{genesisAddress, fromID, Denom, rand.Intn(GenesisSupply)}, + func() {}, + newTransactionResponse(), + false, + }, + {"wrapOneMoreThanSupply", + args{genesisAddress, fromID, Denom, GenesisSupply + 1}, + func() {}, + nil, + true, + }, + {"wrapZero", + args{genesisAddress, fromID, Denom, 0}, + func() {}, + newTransactionResponse(), + false, + }, + {"wrapCoinNotPresent", + args{genesisAddress, fromID, "coinNotPresent", 1}, + func() {}, + nil, + true, + }, + {"wrapCoinNotAuthorized", + args{genesisAddress, fromID, "unauthorizedCoin", 1}, + func() { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin("unauthorizedCoin", sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + }, + nil, + true, + }, + {"wrapCoinNotAuthorized", + args{genesisAddress, fromID, "unauthorizedCoin", 1}, + func() { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin("unauthorizedCoin", sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + }, + nil, + true, + }, + {"wrapInMultiCoinScenario", + args{genesisAddress, fromID, Denom, 1}, + func() { + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + } + }, + newTransactionResponse(), + false, + }, + {"wrapInMultiCoinMultipleAddressScenario", + args{genesisAddress, fromID, Denom, 1}, + func() { + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()), coinSupply) + } + }, + newTransactionResponse(), + false, + }, + {"wrapInMultiAssetScenario", + args{genesisAddress, fromID, Denom, 1}, + func() { + wrapAllowedDenoms := baseData.NewListData(baseData.NewStringData(Denom)) + wrapCoins := sdkTypes.NewCoins() + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + wrapAllowedDenoms = wrapAllowedDenoms.Add(baseData.NewStringData(Denom + strconv.Itoa(i))) + wrapCoins = wrapCoins.Add(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + } + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), wrapAllowedDenoms)))) + _, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(genesisAddress, fromID, wrapCoins).(helpers.Message)) + if err != nil { + t.Error("unexpected error") + } + }, + newTransactionResponse(), + false, + }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - bankKeeper: tt.fields.bankKeeper, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, - mintAuxiliary: tt.fields.mintAuxiliary, + + tt.setup() + + initialSupply := BankKeeper.GetSupply(Context, tt.args.denom).Amount + initialAddressBalance := BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount + + got, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(tt.args.from, tt.args.fromID, sdkTypes.NewCoins(sdkTypes.NewCoin(tt.args.denom, sdkTypes.NewInt(int64(tt.args.amount))))).(helpers.Message)) + + finalSupply := BankKeeper.GetSupply(Context, tt.args.denom).Amount + if !initialSupply.Sub(finalSupply).IsZero() { + t.Error("supply should not change") } - if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) + + finalAddressBalance := BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount + if !tt.wantErr && !initialAddressBalance.Sub(finalAddressBalance).Equal(sdkTypes.NewInt(int64(tt.args.amount))) { + t.Error("unexpected address balance") } - }) - } -} -func Test_transactionKeeper_Transact(t *testing.T) { - setMockBehaviour() - testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.OneInt())) + if !tt.wantErr { + if Mappable := TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Fetch(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())).GetMappable(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())); Mappable == nil { + t.Error("coin asset should have been created") + } + } + + if tt.wantErr && !initialAddressBalance.Equal(finalAddressBalance) { + t.Error("address balance should not have changed") - type args struct { - message sdkTypes.Msg - } - tests := []struct { - name string - args args - want helpers.TransactionResponse - wantErr bool - }{ - {"+ve", args{NewMessage(genesisAddress, fromID, testCoins)}, newTransactionResponse(), false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - moduleMapper, - parameterManager, - BankKeeper, - authenticateAuxiliary, - mintAuxiliary, } - got, err := transactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), tt.args.message.(helpers.Message)) + if (err != nil) != tt.wantErr { - t.Errorf("Transact() error = %v, wantErr %v", err, tt.wantErr) - return + t.Error("unexpected error") } + if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Transact() got = %v, want %v", got, tt.want) + t.Error("unexpected response") } }) } From 4a4efb546287e03f9b790f986b066dd0729bcf28 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Mon, 25 Mar 2024 21:34:22 +0530 Subject: [PATCH 19/57] feat(assets): adding max list length validation --- x/assets/constants/validations.go | 3 +++ x/assets/transactions/unwrap/message.go | 5 +++++ x/assets/transactions/wrap/message.go | 5 +++++ 3 files changed, 13 insertions(+) create mode 100644 x/assets/constants/validations.go diff --git a/x/assets/constants/validations.go b/x/assets/constants/validations.go new file mode 100644 index 000000000..ab104a8c1 --- /dev/null +++ b/x/assets/constants/validations.go @@ -0,0 +1,3 @@ +package constants + +const MaxListLength = 10 diff --git a/x/assets/transactions/unwrap/message.go b/x/assets/transactions/unwrap/message.go index 36ea47023..9e124f65f 100644 --- a/x/assets/transactions/unwrap/message.go +++ b/x/assets/transactions/unwrap/message.go @@ -4,7 +4,9 @@ package unwrap import ( + "github.com/AssetMantle/modules/x/assets/constants" codecUtilities "github.com/AssetMantle/schema/go/codec/utilities" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" baseIDs "github.com/AssetMantle/schema/go/ids/base" "github.com/cosmos/cosmos-sdk/codec" @@ -34,6 +36,9 @@ func (message *Message) ValidateBasic() error { if err := message.Coins.Validate(); err != nil { return err } + if message.Coins.Len() > constants.MaxListLength { + return errorConstants.InvalidRequest.Wrapf("coins length %d exceeds max length %d", message.Coins.Len(), constants.MaxListLength) + } return nil } func (message *Message) GetSigners() []sdkTypes.AccAddress { diff --git a/x/assets/transactions/wrap/message.go b/x/assets/transactions/wrap/message.go index dacf68abd..4e75bd197 100644 --- a/x/assets/transactions/wrap/message.go +++ b/x/assets/transactions/wrap/message.go @@ -4,7 +4,9 @@ package wrap import ( + "github.com/AssetMantle/modules/x/assets/constants" codecUtilities "github.com/AssetMantle/schema/go/codec/utilities" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" baseIDs "github.com/AssetMantle/schema/go/ids/base" "github.com/cosmos/cosmos-sdk/codec" @@ -34,6 +36,9 @@ func (message *Message) ValidateBasic() error { if err := message.Coins.Validate(); err != nil { return err } + if message.Coins.Len() > constants.MaxListLength { + return errorConstants.InvalidRequest.Wrapf("coins length %d exceeds max length %d", message.Coins.Len(), constants.MaxListLength) + } return nil } func (message *Message) GetSigners() []sdkTypes.AccAddress { From 9f2a98418ef37675ef63db3a53e48e70c1dbbe48 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 26 Mar 2024 18:40:20 +0530 Subject: [PATCH 20/57] feat(wrap): optimizing code execution --- .../transactions/wrap/transaction_keeper.go | 51 +++++++++++++++---- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper.go b/x/assets/transactions/wrap/transaction_keeper.go index cf6bd0d6b..16c615eab 100644 --- a/x/assets/transactions/wrap/transaction_keeper.go +++ b/x/assets/transactions/wrap/transaction_keeper.go @@ -33,6 +33,32 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes return transactionKeeper.Handle(context, message.(*Message)) } +// Handle is a method of the transactionKeeper struct. It processes the transaction message passed to it. +// +// Parameters: +// - context (context.Context): Used for timing, cancelation signals, and carrying deadlines, among other things. +// - message (*Message): The transaction message being processed. It should contain details such as the source, destination, and coins involved. +// +// Return values: +// - *TransactionResponse: A response object detailing the result of the transaction. +// - error: In case of an error, this will contain the error message. +// +// The Handle method performs the following steps: +// +// 1. It authenticates the transaction request using the authenticateAuxiliary getter from the transactionKeeper object. If this fails, it returns the error encountered. +// +// 2. It fetches allowed coins from the parameter manager attached to the transactionKeeper object. +// +// 3. For each coin in the transaction message: +// - It first validates the coin asset. If this fails, it returns an error. +// - It then checks whether the coin value is negative. If it is, it returns an error. +// - It checks if the coin is on the list of allowed coins. If it isn't, it returns a not authorized error. +// - It tries to mint the coin using the mintAuxiliary getter of the transactionKeeper object. If this fails, the error is returned. +// - It fetches the coinAsset from the mapper attached to the transactionKeeper. +// - If the coinAsset isn't already in the collection, it is added using a new record. +// - It tries to send the coins from the sender's account to the module account using the bankKeeper attached to transactionKeeper object. If this fails, the error is returned. +// +// 4. If the process completes successfully for all coins, it returns a new transaction response object. func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.GetFromAddress(), message.FromID)); err != nil { return nil, err @@ -41,15 +67,19 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa wrapAllowedCoins := transactionKeeper.parameterManager.Fetch(context).GetParameter(constantProperties.WrapAllowedCoinsProperty.GetID()).GetMetaProperty().GetData().Get().(*base.ListData) for _, coin := range message.Coins { - if _, found := wrapAllowedCoins.Search(base.NewStringData(coin.Denom)); !found { - return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be wrapped", coin.Denom) + coinAsset := baseDocuments.NewCoinAsset(coin.Denom) + + if err := coinAsset.ValidateCoinAsset(); err != nil { + return nil, errorConstants.InvalidParameter.Wrapf("%s", err.Error()) } - if err := transactionKeeper.bankKeeper.SendCoinsFromAccountToModule(sdkTypes.UnwrapSDKContext(context), message.GetFromAddress(), constants.ModuleName, sdkTypes.NewCoins(coin)); err != nil { - return nil, err + if coin.IsNegative() { + return nil, errorConstants.InvalidParameter.Wrapf("coin %s is negative", coin.Denom) } - coinAsset := baseDocuments.NewCoinAsset(coin.Denom) + if _, found := wrapAllowedCoins.Search(base.NewStringData(coin.Denom)); !found { + return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be wrapped", coin.Denom) + } if _, err := transactionKeeper.mintAuxiliary.GetKeeper().Help(context, mint.NewAuxiliaryRequest(message.FromID, coinAsset.GetCoinAssetID(), coin.Amount)); err != nil { return nil, err @@ -57,14 +87,13 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(coinAsset.GetCoinAssetID())) - Mappable := assets.GetMappable(key.NewKey(coinAsset.GetCoinAssetID())) - if Mappable == nil { - if err := coinAsset.ValidateBasic(); err != nil { - return nil, err - } - + if assets.GetMappable(key.NewKey(coinAsset.GetCoinAssetID())) == nil { assets.Add(record.NewRecord(coinAsset)) } + + if err := transactionKeeper.bankKeeper.SendCoinsFromAccountToModule(sdkTypes.UnwrapSDKContext(context), message.GetFromAddress(), constants.ModuleName, sdkTypes.NewCoins(coin)); err != nil { + return nil, err + } } return newTransactionResponse(), nil From 56f56934158e19bb7451061ec08eb305f2c429cd Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 26 Mar 2024 18:40:58 +0530 Subject: [PATCH 21/57] feat(wrap): adding test cases --- .../wrap/transaction_keeper_test.go | 145 +++++++++++------- 1 file changed, 92 insertions(+), 53 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper_test.go b/x/assets/transactions/wrap/transaction_keeper_test.go index 51be0e912..fc97fd1c6 100644 --- a/x/assets/transactions/wrap/transaction_keeper_test.go +++ b/x/assets/transactions/wrap/transaction_keeper_test.go @@ -6,13 +6,18 @@ package wrap import ( "context" "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/mapper" "github.com/AssetMantle/modules/x/assets/parameters" + "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/x/splits/auxiliaries/mint" baseData "github.com/AssetMantle/schema/go/data/base" baseDocuments "github.com/AssetMantle/schema/go/documents/base" - "github.com/AssetMantle/schema/go/ids" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + baseIDs "github.com/AssetMantle/schema/go/ids/base" baseLists "github.com/AssetMantle/schema/go/lists/base" "github.com/AssetMantle/schema/go/parameters/base" baseProperties "github.com/AssetMantle/schema/go/properties/base" @@ -20,6 +25,7 @@ import ( "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -77,11 +83,15 @@ const ( var ( moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) - authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) - _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) + authenticateAuxiliaryFailureAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, authenticate.NewAuxiliaryRequest(authenticateAuxiliaryFailureAddress, baseIDs.PrototypeIdentityID())).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) - mintAuxiliaryKeeper = new(MockAuxiliaryKeeper) - _ = mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + mintAuxiliaryKeeper = new(MockAuxiliaryKeeper) + mintAuxiliaryFailureDenom = "mint" + _ = mintAuxiliaryKeeper.On("Help", mock.Anything, mint.NewAuxiliaryRequest(baseIDs.PrototypeIdentityID(), baseDocuments.NewCoinAsset(mintAuxiliaryFailureDenom).GetCoinAssetID(), sdkTypes.OneInt())).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + _ = mintAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) authenticateAuxiliary = new(MockAuxiliary) _ = authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) @@ -136,7 +146,6 @@ func setContext() sdkTypes.Context { func TestTransactionKeeperTransact(t *testing.T) { type args struct { from sdkTypes.AccAddress - fromID ids.IdentityID denom string amount int } @@ -145,60 +154,84 @@ func TestTransactionKeeperTransact(t *testing.T) { args args setup func() want *TransactionResponse - wantErr bool + wantErr errors.Error }{ {"wrapOne", - args{genesisAddress, fromID, Denom, 1}, + args{genesisAddress, Denom, 1}, func() {}, newTransactionResponse(), - false, + nil, }, {"wrapRandom", - args{genesisAddress, fromID, Denom, rand.Intn(GenesisSupply)}, + args{genesisAddress, Denom, rand.Intn(GenesisSupply)}, func() {}, newTransactionResponse(), - false, + nil, }, {"wrapOneMoreThanSupply", - args{genesisAddress, fromID, Denom, GenesisSupply + 1}, + args{genesisAddress, Denom, GenesisSupply + 1}, + func() {}, + nil, + sdkErrors.ErrInsufficientFunds, + }, + { + "wrapNegative", + args{genesisAddress, Denom, -1}, + func() {}, + nil, + errorConstants.InvalidParameter, + }, + { + "wrapInvalidDenom", + args{genesisAddress, random.GenerateUniqueIdentifier(), 1}, + func() {}, + nil, + errorConstants.InvalidParameter, + }, + { + "identityAuthenticationFailure", + args{authenticateAuxiliaryFailureAddress, Denom, 1}, func() {}, nil, - true, + errorConstants.MockError, }, - {"wrapZero", - args{genesisAddress, fromID, Denom, 0}, + { + "wrapZero", + args{genesisAddress, Denom, 0}, func() {}, newTransactionResponse(), - false, + nil, }, - {"wrapCoinNotPresent", - args{genesisAddress, fromID, "coinNotPresent", 1}, + { + "wrapCoinNotPresent", + args{genesisAddress, "coinNotPresent", 1}, func() {}, nil, - true, + errorConstants.NotAuthorized, }, - {"wrapCoinNotAuthorized", - args{genesisAddress, fromID, "unauthorizedCoin", 1}, + { + "wrapCoinNotAuthorized", + args{genesisAddress, "unauthorizedCoin", 1}, func() { coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin("unauthorizedCoin", sdkTypes.NewInt(GenesisSupply))) _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) }, nil, - true, + errorConstants.NotAuthorized, }, - {"wrapCoinNotAuthorized", - args{genesisAddress, fromID, "unauthorizedCoin", 1}, + { + "mintAuxiliaryFailure", + args{genesisAddress, mintAuxiliaryFailureDenom, 1}, func() { - coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin("unauthorizedCoin", sdkTypes.NewInt(GenesisSupply))) - _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) - _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(mintAuxiliaryFailureDenom), baseData.NewStringData(Denom)))))) }, nil, - true, + errorConstants.MockError, }, - {"wrapInMultiCoinScenario", - args{genesisAddress, fromID, Denom, 1}, + { + "wrapInMultiCoinScenario", + args{genesisAddress, Denom, 1}, func() { for i := 0; i < 1000; i++ { coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) @@ -207,10 +240,11 @@ func TestTransactionKeeperTransact(t *testing.T) { } }, newTransactionResponse(), - false, + nil, }, - {"wrapInMultiCoinMultipleAddressScenario", - args{genesisAddress, fromID, Denom, 1}, + { + "wrapInMultiCoinMultipleAddressScenario", + args{genesisAddress, Denom, 1}, func() { for i := 0; i < 1000; i++ { coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) @@ -219,10 +253,11 @@ func TestTransactionKeeperTransact(t *testing.T) { } }, newTransactionResponse(), - false, + nil, }, - {"wrapInMultiAssetScenario", - args{genesisAddress, fromID, Denom, 1}, + { + "wrapInMultiAssetScenario", + args{genesisAddress, Denom, 1}, func() { wrapAllowedDenoms := baseData.NewListData(baseData.NewStringData(Denom)) wrapCoins := sdkTypes.NewCoins() @@ -234,13 +269,13 @@ func TestTransactionKeeperTransact(t *testing.T) { wrapCoins = wrapCoins.Add(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) } parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), wrapAllowedDenoms)))) - _, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(genesisAddress, fromID, wrapCoins).(helpers.Message)) + _, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(genesisAddress, baseIDs.PrototypeIdentityID(), wrapCoins).(helpers.Message)) if err != nil { t.Error("unexpected error") } }, newTransactionResponse(), - false, + nil, }, } @@ -249,34 +284,38 @@ func TestTransactionKeeperTransact(t *testing.T) { tt.setup() - initialSupply := BankKeeper.GetSupply(Context, tt.args.denom).Amount - initialAddressBalance := BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount - - got, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(tt.args.from, tt.args.fromID, sdkTypes.NewCoins(sdkTypes.NewCoin(tt.args.denom, sdkTypes.NewInt(int64(tt.args.amount))))).(helpers.Message)) - - finalSupply := BankKeeper.GetSupply(Context, tt.args.denom).Amount - if !initialSupply.Sub(finalSupply).IsZero() { - t.Error("supply should not change") + var initialSupply, initialAddressBalance, finalSupply, finalAddressBalance sdkTypes.Int + if sdkTypes.ValidateDenom(tt.args.denom) == nil { + initialSupply = BankKeeper.GetSupply(Context, tt.args.denom).Amount + initialAddressBalance = BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount } + got, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(tt.args.from, baseIDs.PrototypeIdentityID(), sdkTypes.Coins{sdkTypes.Coin{Denom: tt.args.denom, Amount: sdkTypes.NewInt(int64(tt.args.amount))}}).(helpers.Message)) - finalAddressBalance := BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount - if !tt.wantErr && !initialAddressBalance.Sub(finalAddressBalance).Equal(sdkTypes.NewInt(int64(tt.args.amount))) { - t.Error("unexpected address balance") + if sdkTypes.ValidateDenom(tt.args.denom) == nil { + finalSupply = BankKeeper.GetSupply(Context, tt.args.denom).Amount + if !initialSupply.Sub(finalSupply).IsZero() { + t.Error("supply should not change") + } + + finalAddressBalance = BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount + if tt.wantErr == nil && !initialAddressBalance.Sub(finalAddressBalance).Equal(sdkTypes.NewInt(int64(tt.args.amount))) { + t.Error("unexpected address balance") + } } - if !tt.wantErr { + if tt.wantErr == nil { if Mappable := TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Fetch(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())).GetMappable(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())); Mappable == nil { t.Error("coin asset should have been created") } } - if tt.wantErr && !initialAddressBalance.Equal(finalAddressBalance) { + if tt.wantErr != nil && !initialAddressBalance.Equal(finalAddressBalance) { t.Error("address balance should not have changed") } - if (err != nil) != tt.wantErr { - t.Error("unexpected error") + if (err != nil) && !tt.wantErr.Is(err) { + t.Errorf("unexpected error: %v", err) } if !reflect.DeepEqual(got, tt.want) { From f4b6997c2814fdd25f241e84242fcd0f2e45a616 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 26 Mar 2024 20:01:22 +0530 Subject: [PATCH 22/57] minor code optimization --- x/assets/transactions/wrap/transaction_keeper.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/x/assets/transactions/wrap/transaction_keeper.go b/x/assets/transactions/wrap/transaction_keeper.go index 16c615eab..c00a7d364 100644 --- a/x/assets/transactions/wrap/transaction_keeper.go +++ b/x/assets/transactions/wrap/transaction_keeper.go @@ -85,9 +85,7 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, err } - assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(coinAsset.GetCoinAssetID())) - - if assets.GetMappable(key.NewKey(coinAsset.GetCoinAssetID())) == nil { + if assets := transactionKeeper.mapper.NewCollection(context); assets.Fetch(key.NewKey(coinAsset.GetCoinAssetID())).GetMappable(key.NewKey(coinAsset.GetCoinAssetID())) == nil { assets.Add(record.NewRecord(coinAsset)) } From 266e0f2ac9608494ede61b92aa067ac2240f824e Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 26 Mar 2024 20:02:18 +0530 Subject: [PATCH 23/57] chore(unwrap): code optimization --- .../transactions/unwrap/transaction_keeper.go | 36 +++++++++---------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/x/assets/transactions/unwrap/transaction_keeper.go b/x/assets/transactions/unwrap/transaction_keeper.go index e102b26bd..4a0183b69 100644 --- a/x/assets/transactions/unwrap/transaction_keeper.go +++ b/x/assets/transactions/unwrap/transaction_keeper.go @@ -5,6 +5,7 @@ package unwrap import ( "context" + "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/schema/go/data/base" baseDocuments "github.com/AssetMantle/schema/go/documents/base" @@ -14,7 +15,6 @@ import ( bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/AssetMantle/modules/helpers" - "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/splits/auxiliaries/burn" @@ -35,38 +35,36 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes } func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress := message.GetFromAddress() - - if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { + if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.GetFromAddress(), message.FromID)); err != nil { return nil, err } - if err := transactionKeeper.bankKeeper.SendCoinsFromModuleToAccount(sdkTypes.UnwrapSDKContext(context), constants.ModuleName, fromAddress, message.Coins); err != nil { - return nil, err - } + unwrapAllowedCoins := transactionKeeper.parameterManager.Fetch(context).GetParameter(constantProperties.UnwrapAllowedCoinsProperty.GetID()).GetMetaProperty().GetData().Get().(*base.ListData) for _, coin := range message.Coins { - if err := sdkTypes.ValidateDenom(coin.Denom); err != nil { - return nil, errorConstants.InvalidRequest.Wrapf("coin denom %s is invalid", coin.Denom) + coinAsset := baseDocuments.NewCoinAsset(coin.Denom) + + if err := coinAsset.ValidateCoinAsset(); err != nil { + return nil, errorConstants.InvalidParameter.Wrapf("%s", err.Error()) } - if _, found := transactionKeeper.parameterManager.Fetch(context).GetParameter(constantProperties.UnwrapAllowedCoinsProperty.GetID()).GetMetaProperty().GetData().Get().(*base.ListData).Search(base.NewStringData(coin.Denom)); !found { - return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be unwrapped", coin.Denom) + if coin.IsNegative() { + return nil, errorConstants.InvalidParameter.Wrapf("coin %s is negative", coin.Denom) } - coinAssetID := baseDocuments.NewCoinAsset(coin.Denom).GetCoinAssetID() + if _, found := unwrapAllowedCoins.Search(base.NewStringData(coin.Denom)); !found { + return nil, errorConstants.NotAuthorized.Wrapf("coin %s is not allowed to be unwrapped", coin.Denom) + } - Mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(coinAssetID)).GetMappable(key.NewKey(coinAssetID)) - if Mappable == nil { - return nil, errorConstants.EntityNotFound.Wrapf("asset %s not found", coinAssetID) + if transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(coinAsset.GetCoinAssetID())).GetMappable(key.NewKey(coinAsset.GetCoinAssetID())) == nil { + return nil, errorConstants.EntityNotFound.Wrapf("asset %s not found", coinAsset.GetDenom()) } - value := coin.Amount - if value.IsNegative() { - return nil, errorConstants.InvalidRequest.Wrapf("coin amount %s is negative", value) + if _, err := transactionKeeper.burnAuxiliary.GetKeeper().Help(context, burn.NewAuxiliaryRequest(message.FromID, coinAsset.GetCoinAssetID(), coin.Amount)); err != nil { + return nil, err } - if _, err := transactionKeeper.burnAuxiliary.GetKeeper().Help(context, burn.NewAuxiliaryRequest(message.FromID, coinAssetID, value)); err != nil { + if err := transactionKeeper.bankKeeper.SendCoinsFromModuleToAccount(sdkTypes.UnwrapSDKContext(context), constants.ModuleName, message.GetFromAddress(), sdkTypes.NewCoins(coin)); err != nil { return nil, err } } From 8314812ea2a3dec87b113bce006c6c770bf052fc Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Tue, 26 Mar 2024 20:03:00 +0530 Subject: [PATCH 24/57] feat(unwrap): adding transaction keeper test case --- .../unwrap/transaction_keeper_test.go | 441 +++++++++++------- 1 file changed, 283 insertions(+), 158 deletions(-) diff --git a/x/assets/transactions/unwrap/transaction_keeper_test.go b/x/assets/transactions/unwrap/transaction_keeper_test.go index 42ac69d99..8e8e45ea5 100644 --- a/x/assets/transactions/unwrap/transaction_keeper_test.go +++ b/x/assets/transactions/unwrap/transaction_keeper_test.go @@ -5,205 +5,330 @@ package unwrap import ( "context" - "fmt" "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/assets/constants" + "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/mapper" - "github.com/AssetMantle/modules/x/classifications/auxiliaries/burn" + "github.com/AssetMantle/modules/x/assets/parameters" + "github.com/AssetMantle/modules/x/assets/record" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" - "github.com/AssetMantle/modules/x/splits/constants" - "github.com/AssetMantle/modules/x/splits/parameters" + "github.com/AssetMantle/modules/x/splits/auxiliaries/burn" + baseData "github.com/AssetMantle/schema/go/data/base" + baseDocuments "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + baseIDs "github.com/AssetMantle/schema/go/ids/base" + baseLists "github.com/AssetMantle/schema/go/lists/base" + "github.com/AssetMantle/schema/go/parameters/base" + baseProperties "github.com/AssetMantle/schema/go/properties/base" + constantProperties "github.com/AssetMantle/schema/go/properties/constants" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/keeper" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/distribution/types" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/require" + paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/stretchr/testify/mock" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "math/rand" "reflect" + "strconv" "testing" ) -var ( - authenticateAuxiliary helpers.Auxiliary - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdkTypes.AccAddress(delPk1.Address()) +type MockAuxiliary struct { + mock.Mock +} + +var _ helpers.Auxiliary = (*MockAuxiliary)(nil) + +func (mockAuxiliary *MockAuxiliary) GetName() string { panic(mockAuxiliary) } +func (mockAuxiliary *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := mockAuxiliary.Called() + return args.Get(0).(helpers.AuxiliaryKeeper) +} +func (mockAuxiliary *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + panic(mockAuxiliary) +} + +type MockAuxiliaryKeeper struct { + mock.Mock +} + +var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) + +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := mockAuxiliaryKeeper.Called(context, request) + return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) +} +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := mockAuxiliaryKeeper.Called(m2, manager, i) + return args.Get(0).(helpers.Keeper) +} + +const ( + TestMinterModuleName = "testMinter" + Denom = "stake" + ChainID = "testChain" + GenesisSupply = 1000000000000 ) -func createTestInput(t *testing.T) (sdkTypes.Context, helpers.Mapper, helpers.ParameterManager, bankKeeper.Keeper, helpers.Auxiliary) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - Codec := baseHelpers.CodecPrototype() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - keyAcc := sdkTypes.NewKVStoreKey(authTypes.StoreKey) - keyDistr := sdkTypes.NewKVStoreKey(types.StoreKey) - keyStaking := sdkTypes.NewKVStoreKey(stakingTypes.StoreKey) - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) +var ( + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) + + authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) + authenticateAuxiliaryFailureAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, authenticate.NewAuxiliaryRequest(authenticateAuxiliaryFailureAddress, baseIDs.PrototypeIdentityID())).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + + burnAuxiliaryKeeper = new(MockAuxiliaryKeeper) + burnAuxiliaryFailureDenom = "burn" + _ = burnAuxiliaryKeeper.On("Help", mock.Anything, burn.NewAuxiliaryRequest(baseIDs.PrototypeIdentityID(), baseDocuments.NewCoinAsset(burnAuxiliaryFailureDenom).GetCoinAssetID(), sdkTypes.OneInt())).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + _ = burnAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + + authenticateAuxiliary = new(MockAuxiliary) + _ = authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) + burnAuxiliary = new(MockAuxiliary) + _ = burnAuxiliary.On("GetKeeper").Return(burnAuxiliaryKeeper) + + encodingConfig = simapp.MakeTestEncodingConfig() + + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) + + authStoreKey = sdkTypes.NewKVStoreKey(authTypes.StoreKey) + moduleAccountPermissions = map[string][]string{TestMinterModuleName: {authTypes.Minter}, constants.ModuleName: nil} + AuthKeeper = authKeeper.NewAccountKeeper(encodingConfig.Marshaler, authStoreKey, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, moduleAccountPermissions) + + bankStoreKey = sdkTypes.NewKVStoreKey(bankTypes.StoreKey) + blacklistedAddresses = map[string]bool{authTypes.NewModuleAddress(TestMinterModuleName).String(): false, authTypes.NewModuleAddress(constants.ModuleName).String(): false} + BankKeeper = bankKeeper.NewBaseKeeper(encodingConfig.Marshaler, bankStoreKey, AuthKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddresses) + + Context = setContext() + + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom, sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + + genesisAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + _ = BankKeeper.SendCoinsFromModuleToModule(Context, TestMinterModuleName, constants.ModuleName, coinSupply) + + parameterManager = parameters.Prototype().Initialize(ParamsKeeper.Subspace(constants.ModuleName).WithKeyTable(parameters.Prototype().GetKeyTable())). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))) + + TransactionKeeper = transactionKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager, BankKeeper, burnAuxiliary, authenticateAuxiliary} + + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(baseDocuments.NewCoinAsset(Denom))) +) + +func setContext() sdkTypes.Context { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(keyDistr, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(keyStaking, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(keyAcc, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(authStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(bankStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - authenticateAuxiliary = authenticate.Auxiliary.Initialize(Mapper, parameterManager) - - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - feeCollectorAcc := authTypes.NewEmptyModuleAccount(authTypes.FeeCollectorName) - notBondedPool := authTypes.NewEmptyModuleAccount(stakingTypes.NotBondedPoolName, authTypes.Burner, authTypes.Staking) - bondPool := authTypes.NewEmptyModuleAccount(stakingTypes.BondedPoolName, authTypes.Burner, authTypes.Staking) - distrAcc := authTypes.NewEmptyModuleAccount(types.ModuleName) - splitAcc := authTypes.NewEmptyModuleAccount(constants.ModuleName) - - blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true - blacklistedAddrs[notBondedPool.GetAddress().String()] = true - blacklistedAddrs[bondPool.GetAddress().String()] = true - blacklistedAddrs[distrAcc.GetAddress().String()] = true - blacklistedAddrs[splitAcc.GetAddress().String()] = true - - accountKeeper := keeper.NewAccountKeeper(Codec.GetProtoCodec(), keyAcc, ParamsKeeper.Subspace(authTypes.ModuleName), authTypes.ProtoBaseAccount, nil) - BankKeeper := bankKeeper.NewBaseKeeper(Codec.GetProtoCodec(), keyAcc, accountKeeper, ParamsKeeper.Subspace(bankTypes.ModuleName), blacklistedAddrs) - - sk := stakingKeeper.NewKeeper(Codec.GetProtoCodec(), keyStaking, accountKeeper, BankKeeper, ParamsKeeper.Subspace(stakingTypes.ModuleName)) - sk.SetParams(Context, stakingTypes.DefaultParams()) - //intToken := sdkTypes.TokensFromConsensusPower(100000000) - //initCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(Context), intToken)) - //testCoin := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", intToken)) - //totalSupply := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(Context), intToken.MulRaw(int64(len(TestAddrs))))) - - // set module accounts - accountKeeper.SetModuleAccount(Context, feeCollectorAcc) - accountKeeper.SetModuleAccount(Context, notBondedPool) - accountKeeper.SetModuleAccount(Context, bondPool) - accountKeeper.SetModuleAccount(Context, distrAcc) - accountKeeper.SetModuleAccount(Context, splitAcc) - - burnAuxiliary := burn.Auxiliary.Initialize(Mapper, parameterManager) - - return Context, Mapper, parameterManager, BankKeeper, burnAuxiliary -} - -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.TransactionKeeper - }{ - {"+ve", transactionKeeper{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) - } - }) - } + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) } -func Test_transactionKeeper_Initialize(t *testing.T) { - _, Mapper, Parameters, BankKeeper, burnAuxiliary := createTestInput(t) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - bankKeeper bankKeeper.Keeper - authenticateAuxiliary helpers.Auxiliary - } +func TestTransactionKeeperTransact(t *testing.T) { type args struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - auxiliaries []interface{} + from sdkTypes.AccAddress + denom string + amount int } tests := []struct { - name string - fields fields - args args - want helpers.Keeper + name string + args args + setup func() + want *TransactionResponse + wantErr errors.Error }{ - {"+ve", fields{Mapper, Parameters, BankKeeper, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, BankKeeper, burnAuxiliary, authenticateAuxiliary}}, + {"unwrapOne", + args{genesisAddress, Denom, 1}, + func() {}, + newTransactionResponse(), + nil, + }, + {"unwrapRandom", + args{genesisAddress, Denom, rand.Intn(GenesisSupply)}, + func() {}, + newTransactionResponse(), + nil, + }, + {"unwrapOneMoreThanSupply", + args{genesisAddress, Denom, GenesisSupply + 1}, + func() {}, + nil, + sdkErrors.ErrInsufficientFunds, + }, + { + "unwrapNegative", + args{genesisAddress, Denom, -1}, + func() {}, + nil, + errorConstants.InvalidParameter, + }, + { + "unwrapInvalidDenom", + args{genesisAddress, random.GenerateUniqueIdentifier(), 1}, + func() {}, + nil, + errorConstants.InvalidParameter, + }, + { + "identityAuthenticationFailure", + args{authenticateAuxiliaryFailureAddress, Denom, 1}, + func() {}, + nil, + errorConstants.MockError, + }, + { + "unwrapZero", + args{genesisAddress, Denom, 0}, + func() {}, + newTransactionResponse(), + nil, + }, + { + "unwrapCoinNotPresent", + args{genesisAddress, "coinNotPresent", 1}, + func() {}, + nil, + errorConstants.NotAuthorized, + }, + { + "unwrapCoinNotAuthorized", + args{genesisAddress, "unauthorizedCoin", 1}, + func() { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin("unauthorizedCoin", sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + }, + nil, + errorConstants.NotAuthorized, + }, + { + "burnAuxiliaryFailure", + args{genesisAddress, burnAuxiliaryFailureDenom, 1}, + func() { + TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(baseDocuments.NewCoinAsset(burnAuxiliaryFailureDenom))) + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(burnAuxiliaryFailureDenom), baseData.NewStringData(Denom)))))) + }, + nil, + errorConstants.MockError, + }, + { + "wrapInMultiCoinScenario", + args{genesisAddress, Denom, 1}, + func() { + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, genesisAddress, coinSupply) + } + }, + newTransactionResponse(), + nil, + }, + { + "wrapInMultiCoinMultipleAddressScenario", + args{genesisAddress, Denom, 1}, + func() { + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToAccount(Context, TestMinterModuleName, sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()), coinSupply) + } + }, + newTransactionResponse(), + nil, + }, + { + "wrapInMultiAssetScenario", + args{genesisAddress, Denom, 1}, + func() { + unwrapAllowedDenoms := baseData.NewListData(baseData.NewStringData(Denom)) + unwrapCoins := sdkTypes.NewCoins() + + for i := 0; i < 1000; i++ { + coinSupply = sdkTypes.NewCoins(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + _ = BankKeeper.MintCoins(Context, TestMinterModuleName, coinSupply) + _ = BankKeeper.SendCoinsFromModuleToModule(Context, TestMinterModuleName, constants.ModuleName, coinSupply) + + TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(baseDocuments.NewCoinAsset(Denom + strconv.Itoa(i)))) + + unwrapAllowedDenoms = unwrapAllowedDenoms.Add(baseData.NewStringData(Denom + strconv.Itoa(i))) + unwrapCoins = unwrapCoins.Add(sdkTypes.NewCoin(Denom+strconv.Itoa(i), sdkTypes.NewInt(GenesisSupply))) + } + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), unwrapAllowedDenoms)))) + _, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(genesisAddress, baseIDs.PrototypeIdentityID(), unwrapCoins).(helpers.Message)) + if err != nil { + t.Errorf("unexpected error %v", err) + } + }, + newTransactionResponse(), + nil, + }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - bankKeeper: tt.fields.bankKeeper, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, + + tt.setup() + + var initialSupply, initialAddressBalance, finalSupply, finalAddressBalance sdkTypes.Int + + if sdkTypes.ValidateDenom(tt.args.denom) == nil { + initialSupply = BankKeeper.GetSupply(Context, tt.args.denom).Amount + initialAddressBalance = BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount + } + got, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(tt.args.from, baseIDs.PrototypeIdentityID(), sdkTypes.Coins{sdkTypes.Coin{Denom: tt.args.denom, Amount: sdkTypes.NewInt(int64(tt.args.amount))}}).(helpers.Message)) + + if sdkTypes.ValidateDenom(tt.args.denom) == nil { + finalSupply = BankKeeper.GetSupply(Context, tt.args.denom).Amount + if !initialSupply.Sub(finalSupply).IsZero() { + t.Error("supply should not change") + } + + finalAddressBalance = BankKeeper.GetBalance(Context, genesisAddress, tt.args.denom).Amount + if tt.wantErr == nil && !finalAddressBalance.Sub(initialAddressBalance).Equal(sdkTypes.NewInt(int64(tt.args.amount))) { + t.Error("unexpected address balance") + } } - if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) + + if tt.wantErr == nil { + if Mappable := TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Fetch(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())).GetMappable(key.NewKey(baseDocuments.NewCoinAsset(tt.args.denom).GetCoinAssetID())); Mappable == nil { + t.Error("coin asset should have been created") + } } - }) - } -} -func Test_transactionKeeper_Transact(t *testing.T) { - Context, Mapper, Parameters, BankKeeper, burnAuxiliary := createTestInput(t) + if tt.wantErr != nil && !initialAddressBalance.Equal(finalAddressBalance) { + t.Error("address balance should not have changed") - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - bankKeeper bankKeeper.Keeper - burnAuxiliary helpers.Auxiliary - authenticateAuxiliary helpers.Auxiliary - } - type args struct { - context context.Context - message sdkTypes.Msg - } - tests := []struct { - name string - fields fields - args args - want helpers.TransactionResponse - wantErr bool - }{ - {"+ve", fields{Mapper, Parameters, BankKeeper, burnAuxiliary, authenticateAuxiliary}, args{Context.Context(), NewMessage(delAddr1, fromID, coins)}, newTransactionResponse(), false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - bankKeeper: tt.fields.bankKeeper, - burnAuxiliary: tt.fields.burnAuxiliary, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, } - got, err := transactionKeeper.Transact(tt.args.context, tt.args.message.(helpers.Message)) - if (err != nil) != tt.wantErr { - t.Errorf("Transact() error = %v, wantErr %v", err, tt.wantErr) - return + + if (err != nil) && !tt.wantErr.Is(err) { + t.Errorf("unexpected error: %v", err) } + if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Transact() got = %v, want %v", got, tt.want) + t.Error("unexpected response") } }) } From 4f416b411ae07ede9835fcb369e6cd40d5654c02 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 27 Mar 2024 15:58:23 +0530 Subject: [PATCH 25/57] chore(unwrap): adding code comments --- .../transactions/unwrap/transaction_keeper.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/x/assets/transactions/unwrap/transaction_keeper.go b/x/assets/transactions/unwrap/transaction_keeper.go index 4a0183b69..68c5df8bf 100644 --- a/x/assets/transactions/unwrap/transaction_keeper.go +++ b/x/assets/transactions/unwrap/transaction_keeper.go @@ -34,6 +34,31 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes return transactionKeeper.Handle(context, message.(*Message)) } +// Handle is a method of the transactionKeeper struct. It processes the transaction message passed to it. +// +// Parameters: +// - context (context.Context): Used for timing, cancellation signals, and carrying deadlines, among other things. +// - message (*Message): The transaction message being processed. It contains information about the coins involved and the source of the transaction. +// +// Return values: +// - *TransactionResponse: A response object detailing the outcome of the transaction. +// - error: In case of an error, this will contain the error message. +// +// The Handle method performs the following steps: +// +// 1. It authenticates the transaction sender using the authenticateAuxiliary getter from the transactionKeeper object. If this fails, it returns the error encountered. +// +// 2. It fetches the list of allowed coins for unwrap operation from the parameter manager attached to the transactionKeeper object. +// +// 3. For each coin mentioned in the transaction message: +// - A new CoinAsset object is created and validated. If this is unsuccessful, it returns an error. +// - It checks whether the coin amount is negative. If it is, it returns an error. +// - Tests whether the coin is in the list of allowed coins for unwrap operation. If not, returns a not authorized error. +// - It fetches the coinAsset from the mapper collection attached to the transactionKeeper. If it's not present, returns an entity not found error. +// - It sends a burn request to the auxiliary to deduct the coin amount from the sender's account. If unsuccessful, the error is returned. +// - It attempts to transfer the coins from the module to the sender's account using the bankKeeper attached to transactionKeeper object. If this fails, the error is returned. +// +// 4. If the process completes successfully for all coins, it returns a new TransactionResponse object. func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.GetFromAddress(), message.FromID)); err != nil { return nil, err From 52193bc971e83b8a5b0b4d3cae26e0905bee44cd Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 27 Mar 2024 21:25:32 +0530 Subject: [PATCH 26/57] chore(send): adding test cases --- .../send/transaction_keeper_test.go | 346 +++++++++++------- 1 file changed, 223 insertions(+), 123 deletions(-) diff --git a/x/assets/transactions/send/transaction_keeper_test.go b/x/assets/transactions/send/transaction_keeper_test.go index 6c489ce1a..c6c544ccb 100644 --- a/x/assets/transactions/send/transaction_keeper_test.go +++ b/x/assets/transactions/send/transaction_keeper_test.go @@ -5,169 +5,269 @@ package send import ( "context" - "fmt" "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/assets/constants" "github.com/AssetMantle/modules/x/assets/mapper" "github.com/AssetMantle/modules/x/assets/parameters" + "github.com/AssetMantle/modules/x/assets/record" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" - "github.com/AssetMantle/modules/x/splits/auxiliaries/transfer" baseData "github.com/AssetMantle/schema/go/data/base" + "github.com/AssetMantle/schema/go/documents" baseDocuments "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "github.com/AssetMantle/schema/go/ids" baseIDs "github.com/AssetMantle/schema/go/ids/base" baseLists "github.com/AssetMantle/schema/go/lists/base" + "github.com/AssetMantle/schema/go/parameters/base" + "github.com/AssetMantle/schema/go/properties" baseProperties "github.com/AssetMantle/schema/go/properties/base" + constantProperties "github.com/AssetMantle/schema/go/properties/constants" baseQualified "github.com/AssetMantle/schema/go/qualified/base" + baseTypes "github.com/AssetMantle/schema/go/types/base" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/stretchr/testify/require" + paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/stretchr/testify/mock" + "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "math/rand" "reflect" "testing" ) -var ( - authenticateAuxiliary helpers.Auxiliary - supplementAuxiliary helpers.Auxiliary - transferAuxiliary helpers.Auxiliary -) +type MockAuxiliary struct { + mock.Mock +} + +var _ helpers.Auxiliary = (*MockAuxiliary)(nil) -func createTestInput(t *testing.T) (sdkTypes.Context, helpers.Mapper, helpers.ParameterManager) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - authenticateAuxiliary = authenticate.Auxiliary.Initialize(Mapper, parameterManager) - supplementAuxiliary = authenticate.Auxiliary.Initialize(Mapper, parameterManager) - transferAuxiliary = transfer.Auxiliary.Initialize(Mapper, parameterManager) - - return Context, Mapper, parameterManager +func (mockAuxiliary *MockAuxiliary) GetName() string { panic(mockAuxiliary) } +func (mockAuxiliary *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := mockAuxiliary.Called() + return args.Get(0).(helpers.AuxiliaryKeeper) +} +func (mockAuxiliary *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + panic(mockAuxiliary) } -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.TransactionKeeper - }{ - {"+ve", transactionKeeper{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) - } - }) - } +type MockAuxiliaryKeeper struct { + mock.Mock } -func Test_transactionKeeper_Initialize(t *testing.T) { - _, Mapper, parameterManager := createTestInput(t) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - authenticateAuxiliary helpers.Auxiliary - } - type args struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - auxiliaries []interface{} - } - tests := []struct { - name string - fields fields - args args - want helpers.Keeper - }{ - {"+ve", fields{Mapper, parameterManager, authenticateAuxiliary}, args{Mapper, parameterManager, []interface{}{}}, transactionKeeper{Mapper, parameterManager, authenticateAuxiliary, supplementAuxiliary, transferAuxiliary}}, +var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) + +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := mockAuxiliaryKeeper.Called(context, request) + return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) +} +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := mockAuxiliaryKeeper.Called(m2, manager, i) + return args.Get(0).(helpers.Keeper) +} + +const ( + Denom = "stake" + ChainID = "testChain" + GenesisSupply = 1000000000000 +) + +var ( + randomMetaPropertyGenerator = func() properties.MetaProperty { + return baseProperties.NewMetaProperty(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewStringData(random.GenerateUniqueIdentifier())) } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, - } - if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) - } - }) + + randomAssetGenerator = func(withImmutable, withMutable properties.MetaProperty) documents.Asset { + return baseDocuments.NewAsset(baseIDs.NewClassificationID(baseQualified.NewImmutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())), baseQualified.NewMutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator()))), baseQualified.NewImmutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())), baseQualified.NewMutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator()))) } -} -func Test_transactionKeeper_Transact(t *testing.T) { - Context, Mapper, parameterManager := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - fromID := baseIDs.NewIdentityID(classificationID, immutables) - testAssetID := baseDocuments.NewCoinAsset("OwnerID").GetCoinAssetID() - testRate := sdkTypes.OneInt() - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, _ := sdkTypes.AccAddressFromBech32(fromAddress) - - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - authenticateAuxiliary helpers.Auxiliary - supplementAuxiliary helpers.Auxiliary - transferAuxiliary helpers.Auxiliary + + fromAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + + asset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))), nil) + assetID = baseIDs.NewAssetID(asset.GetClassificationID(), asset.GetImmutables()).(*baseIDs.AssetID) + + immutableLockAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(-1))), nil) + immutableLockAssetID = baseIDs.NewAssetID(immutableLockAsset.GetClassificationID(), immutableLockAsset.GetImmutables()).(*baseIDs.AssetID) + + mutableLockAsset = randomAssetGenerator(nil, baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(-1)))) + mutableLockAssetID = baseIDs.NewAssetID(mutableLockAsset.GetClassificationID(), mutableLockAsset.GetImmutables()).(*baseIDs.AssetID) + + randomAsset = randomAssetGenerator(nil, nil) + randomAssetID = baseIDs.NewAssetID(randomAsset.GetClassificationID(), randomAsset.GetImmutables()).(*baseIDs.AssetID) + + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) + + authenticateAuxiliaryKeeper = new(MockAuxiliaryKeeper) + authenticateAuxiliaryFailureAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, authenticate.NewAuxiliaryRequest(authenticateAuxiliaryFailureAddress, baseIDs.PrototypeIdentityID())).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + _ = authenticateAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + + authenticateAuxiliary = new(MockAuxiliary) + _ = authenticateAuxiliary.On("GetKeeper").Return(authenticateAuxiliaryKeeper) + + supplementAuxiliaryKeeper = new(MockAuxiliaryKeeper) + + supplementAuxiliaryFailureAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))), nil) + supplementAuxiliaryFailureAssetID = baseIDs.NewAssetID(supplementAuxiliaryFailureAsset.GetClassificationID(), supplementAuxiliaryFailureAsset.GetImmutables()).(*baseIDs.AssetID) + _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + + supplementAuxiliaryAuxiliary = new(MockAuxiliary) + _ = supplementAuxiliaryAuxiliary.On("GetKeeper").Return(supplementAuxiliaryKeeper) + + transferAuxiliaryKeeper = new(MockAuxiliaryKeeper) + + transferAuxiliaryFailureAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))), nil) + transferAuxiliaryFailureAssetID = baseIDs.NewAssetID(transferAuxiliaryFailureAsset.GetClassificationID(), transferAuxiliaryFailureAsset.GetImmutables()).(*baseIDs.AssetID) + _ = transferAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) + + transferAuxiliaryAuxiliary = new(MockAuxiliary) + _ = transferAuxiliaryAuxiliary.On("GetKeeper").Return(transferAuxiliaryKeeper) + + encodingConfig = simapp.MakeTestEncodingConfig() + + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) + + setContext = func() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) } + Context = setContext() + + parameterManager = parameters.Prototype().Initialize(ParamsKeeper.Subspace(constants.ModuleName).WithKeyTable(parameters.Prototype().GetKeyTable())). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.WrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.BurnEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.MintEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.RenumerateEnabledProperty.GetKey(), baseData.NewBooleanData(true))))). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(base.NewParameter(baseProperties.NewMetaProperty(constantProperties.UnwrapAllowedCoinsProperty.GetKey(), baseData.NewListData(baseData.NewStringData(Denom)))))) + + TransactionKeeper = transactionKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager, authenticateAuxiliary, supplementAuxiliaryAuxiliary, transferAuxiliaryAuxiliary} + + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(asset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(supplementAuxiliaryFailureAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(transferAuxiliaryFailureAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(immutableLockAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(mutableLockAsset)) +) + +func TestTransactionKeeperTransact(t *testing.T) { type args struct { - context context.Context - message helpers.Message + from sdkTypes.AccAddress + assetID ids.AssetID + value int } tests := []struct { name string - fields fields args args - want helpers.TransactionResponse - wantErr bool + setup func() + want *TransactionResponse + wantErr errors.Error }{ - {"+ve", fields{Mapper, parameterManager, authenticateAuxiliary, supplementAuxiliary, transferAuxiliary}, args{Context.Context(), NewMessage(fromAccAddress, fromID, fromID, testAssetID, testRate).(*Message)}, newTransactionResponse(), true}, + {"sendOne", + args{fromAddress, assetID, 1}, + func() {}, + newTransactionResponse(), + nil, + }, + {"sendRandom", + args{fromAddress, assetID, rand.Intn(GenesisSupply)}, + func() {}, + newTransactionResponse(), + nil, + }, + { + "sendNegative", + args{fromAddress, assetID, -1}, + func() {}, + nil, + errorConstants.InvalidParameter, + }, + { + "sendAssetNotPresent", + args{fromAddress, randomAssetID, 1}, + func() {}, + nil, + errorConstants.EntityNotFound, + }, + { + "identityAuthenticationFailure", + args{authenticateAuxiliaryFailureAddress, assetID, 1}, + func() {}, + nil, + errorConstants.MockError, + }, + { + "sendZero", + args{fromAddress, assetID, 0}, + func() {}, + newTransactionResponse(), + nil, + }, + { + "sendAssetWithImmutableLock", + args{fromAddress, immutableLockAssetID, 1}, + func() { + }, + nil, + errorConstants.NotAuthorized, + }, + { + "sendAssetWithMutableLock", + args{fromAddress, mutableLockAssetID, 1}, + func() { + }, + nil, + errorConstants.NotAuthorized, + }, + { + "supplementAuxiliaryFailure", + args{fromAddress, supplementAuxiliaryFailureAssetID, 1}, + func() { + }, + nil, + errorConstants.MockError, + }, { + "transferAuxiliaryFailure", + args{fromAddress, transferAuxiliaryFailureAssetID, 1}, + func() { + }, + nil, + errorConstants.MockError, + }, + { + "sendInMultiAssetScenario", + args{fromAddress, assetID, 1}, + func() { + }, + newTransactionResponse(), + nil, + }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - transactionKeeper := transactionKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - authenticateAuxiliary: tt.fields.authenticateAuxiliary, - supplementAuxiliary: tt.fields.supplementAuxiliary, - transferAuxiliary: tt.fields.transferAuxiliary, - } - got, err := transactionKeeper.Transact(tt.args.context, tt.args.message) - if (err != nil) != tt.wantErr { - t.Errorf("Transact() error = %v, wantErr %v", err, tt.wantErr) - return + + tt.setup() + + got, err := TransactionKeeper.Transact(sdkTypes.WrapSDKContext(Context), NewMessage(tt.args.from, baseIDs.PrototypeIdentityID(), baseIDs.PrototypeIdentityID(), tt.args.assetID, sdkTypes.NewInt(int64(tt.args.value))).(helpers.Message)) + + if (tt.wantErr != nil && !tt.wantErr.Is(err)) || (tt.wantErr == nil && err != nil) { + t.Errorf("unexpected error: %v", err) } + if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Transact() got = %v, want %v", got, tt.want) + t.Error("unexpected response") } }) } From fa66ea66724fe0bf2a46e2cce9a43e86cfd0731e Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 28 Mar 2024 16:33:53 +0530 Subject: [PATCH 27/57] chore(send): optimizing keeper code execution and adding code documentation --- .../transactions/send/transaction_keeper.go | 61 +++++++++++++------ 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/x/assets/transactions/send/transaction_keeper.go b/x/assets/transactions/send/transaction_keeper.go index 685a2383f..9f354dc6b 100644 --- a/x/assets/transactions/send/transaction_keeper.go +++ b/x/assets/transactions/send/transaction_keeper.go @@ -5,20 +5,17 @@ package send import ( "context" - - "github.com/AssetMantle/schema/go/data" - errorConstants "github.com/AssetMantle/schema/go/errors/constants" - "github.com/AssetMantle/schema/go/properties" - propertyConstants "github.com/AssetMantle/schema/go/properties/constants" - baseTypes "github.com/AssetMantle/schema/go/types/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/assets/key" "github.com/AssetMantle/modules/x/assets/mappable" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" "github.com/AssetMantle/modules/x/metas/auxiliaries/supplement" "github.com/AssetMantle/modules/x/splits/auxiliaries/transfer" + "github.com/AssetMantle/schema/go/data" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "github.com/AssetMantle/schema/go/properties" + propertyConstants "github.com/AssetMantle/schema/go/properties/constants" + baseTypes "github.com/AssetMantle/schema/go/types/base" ) type transactionKeeper struct { @@ -35,16 +32,51 @@ func (transactionKeeper transactionKeeper) Transact(context context.Context, mes return transactionKeeper.Handle(context, message.(*Message)) } +// Handle is a method of the transactionKeeper struct. It processes the transaction message passed to it. +// +// Parameters: +// - context (context.Context): Used for process synchronization and carrying deadlines, among other things. +// - message (*Message): The transaction message being processed. It should contain details such as the source, destination, and the asset involved. +// +// Return values: +// - *TransactionResponse: A response object detailing the result of the transaction. +// - error: In case of an error, this will contain the error message. +// +// The Handle method performs the following steps: +// +// 1. It authenticates the transaction request using the authenticateAuxiliary getter from the transactionKeeper object. If this fails, it returns the error encountered. +// +// 2. It extracts the value from the message as an integer. If there's an error in this operation, it returns the error encountered. +// +// 3. It fetches the asset from the mapper attached to the transactionKeeper object using the asset ID from the message. +// - If the asset does not exist, it returns an EntityNotFound error. +// +// 4. It checks the asset's lock height property. +// - If the property exists and is not a meta property, it makes a call to supplementAuxiliary's Help method with the lock height property. +// - If the returned lock height property is a meta property, it updates the lock height. +// - If the property isn't a meta property, it returns a MetaDataError error. +// +// 5. If the lock height is greater than the current context height, it returns a NotAuthorized error. +// +// 6. It attempts to perform a transfer via the transferAuxiliary's Help method. +// - If an error occurs during the transfer, it returns the error. +// +// 7. If the process completes successfully, it returns a new transaction response object. +// +// Note: The errorConstants and propertyConstants are used for error handling and property checking respectively. func (transactionKeeper transactionKeeper) Handle(context context.Context, message *Message) (*TransactionResponse, error) { - fromAddress := message.GetFromAddress() + if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.GetFromAddress(), message.FromID)); err != nil { + return nil, err + } - if _, err := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(fromAddress, message.FromID)); err != nil { + value, err := message.GetValueAsInt() + if err != nil { return nil, err } - assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.AssetID)) + assets := transactionKeeper.mapper.NewCollection(context) - Mappable := assets.GetMappable(key.NewKey(message.AssetID)) + Mappable := assets.Fetch(key.NewKey(message.AssetID)).GetMappable(key.NewKey(message.AssetID)) if Mappable == nil { return nil, errorConstants.EntityNotFound.Wrapf("asset with ID %s not found", message.AssetID.AsString()) } @@ -69,11 +101,6 @@ func (transactionKeeper transactionKeeper) Handle(context context.Context, messa return nil, errorConstants.NotAuthorized.Wrapf("transfer is not allowed until height %d", lockHeight.Get()) } - value, ok := sdkTypes.NewIntFromString(message.Value) - if !ok || value.IsNegative() { - return nil, errorConstants.IncorrectFormat.Wrapf("invalid value %s", message.Value) - } - if _, err := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(message.FromID, message.ToID, message.AssetID, value)); err != nil { return nil, err } From 727e4b5ccb0f76bfc1cbd3e27cc9bb7a3d7ca6a1 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 28 Mar 2024 16:34:34 +0530 Subject: [PATCH 28/57] test(send): adding test cases --- .../send/transaction_keeper_test.go | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/x/assets/transactions/send/transaction_keeper_test.go b/x/assets/transactions/send/transaction_keeper_test.go index c6c544ccb..df5edb4ae 100644 --- a/x/assets/transactions/send/transaction_keeper_test.go +++ b/x/assets/transactions/send/transaction_keeper_test.go @@ -12,6 +12,8 @@ import ( "github.com/AssetMantle/modules/x/assets/parameters" "github.com/AssetMantle/modules/x/assets/record" "github.com/AssetMantle/modules/x/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/x/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/x/splits/auxiliaries/transfer" baseData "github.com/AssetMantle/schema/go/data/base" "github.com/AssetMantle/schema/go/documents" baseDocuments "github.com/AssetMantle/schema/go/documents/base" @@ -82,8 +84,10 @@ var ( return baseProperties.NewMetaProperty(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewStringData(random.GenerateUniqueIdentifier())) } - randomAssetGenerator = func(withImmutable, withMutable properties.MetaProperty) documents.Asset { - return baseDocuments.NewAsset(baseIDs.NewClassificationID(baseQualified.NewImmutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())), baseQualified.NewMutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator()))), baseQualified.NewImmutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())), baseQualified.NewMutables(baseLists.NewPropertyList(randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator()))) + randomAssetGenerator = func(withImmutable, withMutable properties.Property) documents.Asset { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(withImmutable, randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(withMutable, randomMetaPropertyGenerator(), randomMetaPropertyGenerator(), randomMetaPropertyGenerator())) + return baseDocuments.NewAsset(baseIDs.NewClassificationID(immutables, mutables), immutables, mutables) } fromAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) @@ -112,8 +116,15 @@ var ( supplementAuxiliaryKeeper = new(MockAuxiliaryKeeper) - supplementAuxiliaryFailureAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))), nil) + supplementAuxiliaryFailureAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))).ScrubData(), nil) supplementAuxiliaryFailureAssetID = baseIDs.NewAssetID(supplementAuxiliaryFailureAsset.GetClassificationID(), supplementAuxiliaryFailureAsset.GetImmutables()).(*baseIDs.AssetID) + _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, supplement.NewAuxiliaryRequest(supplementAuxiliaryFailureAsset.GetProperty(constantProperties.LockHeightProperty.GetID()))).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) + mesaLockAsset = randomAssetGenerator(baseProperties.NewMesaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(1))), nil) + mesaLockAssetID = baseIDs.NewAssetID(mesaLockAsset.GetClassificationID(), mesaLockAsset.GetImmutables()).(*baseIDs.AssetID) + _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, supplement.NewAuxiliaryRequest(mesaLockAsset.GetProperty(constantProperties.LockHeightProperty.GetID()))).Return(supplement.NewAuxiliaryResponse(baseLists.NewPropertyList(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(1))))), nil) + unrevealedLockAsset = randomAssetGenerator(baseProperties.NewMesaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(2))), nil) + unrevealedLockAssetID = baseIDs.NewAssetID(unrevealedLockAsset.GetClassificationID(), unrevealedLockAsset.GetImmutables()).(*baseIDs.AssetID) + _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, supplement.NewAuxiliaryRequest(unrevealedLockAsset.GetProperty(constantProperties.LockHeightProperty.GetID()))).Return(supplement.NewAuxiliaryResponse(baseLists.NewPropertyList()), nil) _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) supplementAuxiliaryAuxiliary = new(MockAuxiliary) @@ -123,6 +134,7 @@ var ( transferAuxiliaryFailureAsset = randomAssetGenerator(baseProperties.NewMetaProperty(constantProperties.LockHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(0))), nil) transferAuxiliaryFailureAssetID = baseIDs.NewAssetID(transferAuxiliaryFailureAsset.GetClassificationID(), transferAuxiliaryFailureAsset.GetImmutables()).(*baseIDs.AssetID) + _ = transferAuxiliaryKeeper.On("Help", mock.Anything, transfer.NewAuxiliaryRequest(baseIDs.PrototypeIdentityID(), baseIDs.PrototypeIdentityID(), transferAuxiliaryFailureAssetID, sdkTypes.NewInt(1))).Return(new(helpers.AuxiliaryResponse), errorConstants.MockError) _ = transferAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(new(helpers.AuxiliaryResponse), nil) transferAuxiliaryAuxiliary = new(MockAuxiliary) @@ -159,6 +171,8 @@ var ( _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(transferAuxiliaryFailureAsset)) _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(immutableLockAsset)) _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(mutableLockAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(mesaLockAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(unrevealedLockAsset)) ) func TestTransactionKeeperTransact(t *testing.T) { @@ -230,6 +244,24 @@ func TestTransactionKeeperTransact(t *testing.T) { nil, errorConstants.NotAuthorized, }, + { + "sendAssetWithMesaLock", + args{fromAddress, mesaLockAssetID, 1}, + func() { + Context = Context.WithBlockHeight(2) + }, + newTransactionResponse(), + nil, + }, + { + "sendAssetWithUnrevealedLock", + args{fromAddress, unrevealedLockAssetID, 1}, + func() { + + }, + nil, + errorConstants.MetaDataError, + }, { "supplementAuxiliaryFailure", args{fromAddress, supplementAuxiliaryFailureAssetID, 1}, @@ -249,6 +281,9 @@ func TestTransactionKeeperTransact(t *testing.T) { "sendInMultiAssetScenario", args{fromAddress, assetID, 1}, func() { + for i := 0; i < 10000; i++ { + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(randomAssetGenerator(nil, nil))) + } }, newTransactionResponse(), nil, From 64526602d931c0f0d2534e84985877f463c0261a Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 28 Mar 2024 16:35:27 +0530 Subject: [PATCH 29/57] test(send): request test optimization --- .../send/transaction_request_test.go | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/x/assets/transactions/send/transaction_request_test.go b/x/assets/transactions/send/transaction_request_test.go index 4cd72a48b..45d276a1d 100644 --- a/x/assets/transactions/send/transaction_request_test.go +++ b/x/assets/transactions/send/transaction_request_test.go @@ -6,15 +6,10 @@ package send import ( "encoding/json" "fmt" - baseDocuments "github.com/AssetMantle/schema/go/documents/base" "reflect" "testing" - baseData "github.com/AssetMantle/schema/go/data/base" baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types" @@ -28,14 +23,9 @@ import ( ) var ( - fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) - testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} - immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData()))) - classificationID = baseIDs.NewClassificationID(immutables, mutables) - fromID = baseIDs.NewIdentityID(classificationID, immutables).(*baseIDs.IdentityID) - assetID = baseDocuments.NewCoinAsset("assetID").GetCoinAssetID().(*baseIDs.AssetID) + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress.String()) + testBaseRequest = rest.BaseReq{From: fromAddress.String(), ChainID: "test", Fees: types.NewCoins()} + fromID = baseIDs.PrototypeIdentityID().(*baseIDs.IdentityID) testRate = types.OneInt() ) From 145778e6c21e8c85a98000bd0ba9834699868b52 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 28 Mar 2024 17:18:09 +0530 Subject: [PATCH 30/57] feat(send): adding getValueAsInt helper method to message --- x/assets/transactions/send/message.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/x/assets/transactions/send/message.go b/x/assets/transactions/send/message.go index 2912d5ad0..5f41007a7 100644 --- a/x/assets/transactions/send/message.go +++ b/x/assets/transactions/send/message.go @@ -17,6 +17,16 @@ import ( var _ helpers.Message = (*Message)(nil) +func (message *Message) GetValueAsInt() (sdkTypes.Int, error) { + value, ok := sdkTypes.NewIntFromString(message.Value) + if !ok { + return sdkTypes.ZeroInt(), errorConstants.IncorrectFormat.Wrapf("send value %s is not a valid integer", message.Value) + } else if value.IsNegative() { + return sdkTypes.ZeroInt(), errorConstants.InvalidParameter.Wrapf("invalid value %s", message.Value) + } + + return value, nil +} func (message *Message) Type() string { return Transaction.GetName() } func (message *Message) GetFromAddress() sdkTypes.AccAddress { from, err := sdkTypes.AccAddressFromBech32(message.From) @@ -38,8 +48,8 @@ func (message *Message) ValidateBasic() error { if err := message.AssetID.ValidateBasic(); err != nil { return err } - if _, ok := sdkTypes.NewIntFromString(message.Value); !ok { - return errorConstants.IncorrectFormat.Wrapf("send value %s is not a valid integer", message.Value) + if _, err := message.GetValueAsInt(); err != nil { + return err } return nil } From 175a86e37ebc907d1e274d802d12d1b3c23c365a Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Thu, 28 Mar 2024 17:24:53 +0530 Subject: [PATCH 31/57] feat(supplement): making auxiliary response public for testing --- x/metas/auxiliaries/supplement/auxiliary_keeper.go | 2 +- x/metas/auxiliaries/supplement/auxiliary_keeper_test.go | 2 +- x/metas/auxiliaries/supplement/auxiliary_response.go | 2 +- x/metas/auxiliaries/supplement/auxiliary_response_test.go | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/x/metas/auxiliaries/supplement/auxiliary_keeper.go b/x/metas/auxiliaries/supplement/auxiliary_keeper.go index d1b17634a..ddcf54800 100644 --- a/x/metas/auxiliaries/supplement/auxiliary_keeper.go +++ b/x/metas/auxiliaries/supplement/auxiliary_keeper.go @@ -42,7 +42,7 @@ func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, request hel } } - return newAuxiliaryResponse(propertyList), nil + return NewAuxiliaryResponse(propertyList), nil } func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.ParameterManager, _ []interface{}) helpers.Keeper { diff --git a/x/metas/auxiliaries/supplement/auxiliary_keeper_test.go b/x/metas/auxiliaries/supplement/auxiliary_keeper_test.go index 5a7754f59..5c2e15579 100644 --- a/x/metas/auxiliaries/supplement/auxiliary_keeper_test.go +++ b/x/metas/auxiliaries/supplement/auxiliary_keeper_test.go @@ -88,7 +88,7 @@ func Test_auxiliaryKeeper_Help(t *testing.T) { want helpers.AuxiliaryResponse wantErr bool }{ - {"+ve", fields{Mapper}, args{Context.Context(), NewAuxiliaryRequest(baseLists.AnyPropertiesToProperties(propertiesList.Get()...)...)}, newAuxiliaryResponse(propertiesList), false}, + {"+ve", fields{Mapper}, args{Context.Context(), NewAuxiliaryRequest(baseLists.AnyPropertiesToProperties(propertiesList.Get()...)...)}, NewAuxiliaryResponse(propertiesList), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/x/metas/auxiliaries/supplement/auxiliary_response.go b/x/metas/auxiliaries/supplement/auxiliary_response.go index 638ea8e7a..b2d2a3ff1 100644 --- a/x/metas/auxiliaries/supplement/auxiliary_response.go +++ b/x/metas/auxiliaries/supplement/auxiliary_response.go @@ -16,7 +16,7 @@ type auxiliaryResponse struct { var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) -func newAuxiliaryResponse(metaProperties lists.PropertyList) helpers.AuxiliaryResponse { +func NewAuxiliaryResponse(metaProperties lists.PropertyList) helpers.AuxiliaryResponse { return auxiliaryResponse{ PropertyList: metaProperties, } diff --git a/x/metas/auxiliaries/supplement/auxiliary_response_test.go b/x/metas/auxiliaries/supplement/auxiliary_response_test.go index fd13d924e..a8e0a454c 100644 --- a/x/metas/auxiliaries/supplement/auxiliary_response_test.go +++ b/x/metas/auxiliaries/supplement/auxiliary_response_test.go @@ -19,10 +19,10 @@ func Test_Super_Response(t *testing.T) { metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) metaPropertyList := base.NewPropertyList([]properties.Property{metaProperty}...) - testAuxiliaryResponse := newAuxiliaryResponse(metaPropertyList) + testAuxiliaryResponse := NewAuxiliaryResponse(metaPropertyList) require.Equal(t, auxiliaryResponse{PropertyList: metaPropertyList}, testAuxiliaryResponse) - testAuxiliaryResponse2 := newAuxiliaryResponse(metaPropertyList) + testAuxiliaryResponse2 := NewAuxiliaryResponse(metaPropertyList) require.Equal(t, auxiliaryResponse{PropertyList: nil}, testAuxiliaryResponse2) Properties := GetMetaPropertiesFromResponse(testAuxiliaryResponse) From 6e3865697c3c4fba221c56eabc620b00987afbf8 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Wed, 3 Apr 2024 16:40:43 +0530 Subject: [PATCH 32/57] refactor(property_list): retiring prototype() method --- utilities/rest/id_getters/docs/common.go | 8 ++-- .../define/transaction_request.go | 8 ++-- .../deputize/transaction_request.go | 2 +- .../transactions/mint/transaction_request.go | 8 ++-- .../mutate/transaction_request.go | 4 +- .../classification/query_keeper_test.go | 4 +- .../transactions/define/message_test.go | 48 +++++++++---------- .../define/transaction_request.go | 8 ++-- .../define/transaction_request_test.go | 4 +- .../transactions/deputize/message_test.go | 2 +- .../deputize/transaction_request.go | 2 +- .../transactions/issue/message_test.go | 8 ++-- .../transactions/issue/transaction_request.go | 8 ++-- .../issue/transaction_request_test.go | 8 ++-- .../update/transaction_request.go | 4 +- .../update/transaction_request_test.go | 4 +- .../deputize/auxiliary_keeper_test.go | 2 +- .../revoke/auxiliary_keeper_test.go | 2 +- .../define/transaction_request.go | 8 ++-- .../define/transaction_request_test.go | 8 ++-- .../transactions/deputize/message_test.go | 2 +- .../deputize/transaction_request.go | 2 +- .../deputize/transaction_request_test.go | 2 +- .../immediate/transaction_request.go | 8 ++-- .../immediate/transaction_request_test.go | 8 ++-- .../transactions/make/transaction_request.go | 8 ++-- .../make/transaction_request_test.go | 8 ++-- .../modify/transaction_request.go | 4 +- .../modify/transaction_request_test.go | 8 ++-- .../put/transaction_request_test.go | 8 ++-- 30 files changed, 104 insertions(+), 104 deletions(-) diff --git a/utilities/rest/id_getters/docs/common.go b/utilities/rest/id_getters/docs/common.go index bb4f7919b..07518b2f5 100644 --- a/utilities/rest/id_getters/docs/common.go +++ b/utilities/rest/id_getters/docs/common.go @@ -50,15 +50,15 @@ func read(context client.Context, responseWriter http.ResponseWriter, httpReques req := transactionRequest.(request) - immutableMetaProperties, _ := baseLists.PrototypePropertyList().FromMetaPropertiesString(req.ImmutableMetaProperties) + immutableMetaProperties, _ := baseLists.NewPropertyList().FromMetaPropertiesString(req.ImmutableMetaProperties) - immutableProperties, _ := baseLists.PrototypePropertyList().FromMetaPropertiesString(req.ImmutableProperties) + immutableProperties, _ := baseLists.NewPropertyList().FromMetaPropertiesString(req.ImmutableProperties) immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, _ := baseLists.PrototypePropertyList().FromMetaPropertiesString(req.MutableMetaProperties) + mutableMetaProperties, _ := baseLists.NewPropertyList().FromMetaPropertiesString(req.MutableMetaProperties) - mutableProperties, _ := baseLists.PrototypePropertyList().FromMetaPropertiesString(req.MutableProperties) + mutableProperties, _ := baseLists.NewPropertyList().FromMetaPropertiesString(req.MutableProperties) mutableProperties = mutableProperties.ScrubData() diff --git a/x/assets/transactions/define/transaction_request.go b/x/assets/transactions/define/transaction_request.go index 5179b5fcc..6d982d947 100644 --- a/x/assets/transactions/define/transaction_request.go +++ b/x/assets/transactions/define/transaction_request.go @@ -74,23 +74,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/assets/transactions/deputize/transaction_request.go b/x/assets/transactions/deputize/transaction_request.go index 59d872ceb..e905c7342 100644 --- a/x/assets/transactions/deputize/transaction_request.go +++ b/x/assets/transactions/deputize/transaction_request.go @@ -84,7 +84,7 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - maintainedProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) + maintainedProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) if err != nil { return nil, err } diff --git a/x/assets/transactions/mint/transaction_request.go b/x/assets/transactions/mint/transaction_request.go index 3970759b2..de30c67a4 100644 --- a/x/assets/transactions/mint/transaction_request.go +++ b/x/assets/transactions/mint/transaction_request.go @@ -78,23 +78,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/assets/transactions/mutate/transaction_request.go b/x/assets/transactions/mutate/transaction_request.go index ec72088a4..7a3c18210 100644 --- a/x/assets/transactions/mutate/transaction_request.go +++ b/x/assets/transactions/mutate/transaction_request.go @@ -72,12 +72,12 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/classifications/queries/classification/query_keeper_test.go b/x/classifications/queries/classification/query_keeper_test.go index 8bcebb53e..0357ab911 100644 --- a/x/classifications/queries/classification/query_keeper_test.go +++ b/x/classifications/queries/classification/query_keeper_test.go @@ -64,9 +64,9 @@ func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { func Test_Query_Keeper_Classification(t *testing.T) { context, keepers := CreateTestInput2(t) - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) - mutableProperties, Error2 := base.PrototypePropertyList().FromMetaPropertiesString("burn:S|100") + mutableProperties, Error2 := base.NewPropertyList().FromMetaPropertiesString("burn:S|100") require.Equal(t, nil, Error2) classificationID := baseIDs.NewClassificationID(baseQualified.NewImmutables(immutableProperties), baseQualified.NewMutables(mutableProperties)) diff --git a/x/identities/transactions/define/message_test.go b/x/identities/transactions/define/message_test.go index a83884328..124db99a1 100644 --- a/x/identities/transactions/define/message_test.go +++ b/x/identities/transactions/define/message_test.go @@ -35,19 +35,19 @@ func Test_messageFromInterface(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) @@ -97,19 +97,19 @@ func Test_message_GetSigners(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) @@ -146,19 +146,19 @@ func Test_message_RegisterCodec(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) @@ -196,19 +196,19 @@ func Test_message_Type(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) @@ -245,19 +245,19 @@ func Test_message_ValidateBasic(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) @@ -294,19 +294,19 @@ func Test_NewMessage(t *testing.T) { fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) immutableMetaProperties := immutableMetaPropertiesInterface.(*baseLists.PropertyList) - immutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) immutableProperties := immutablePropertiesInterface.(*baseLists.PropertyList) - mutableMetaPropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaPropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) mutableMetaProperties := mutableMetaPropertiesInterface.(*baseLists.PropertyList) - mutablePropertiesInterface, err := baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutablePropertiesInterface, err := baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) mutableProperties := mutablePropertiesInterface.(*baseLists.PropertyList) diff --git a/x/identities/transactions/define/transaction_request.go b/x/identities/transactions/define/transaction_request.go index 21a72e974..5f369b1a4 100644 --- a/x/identities/transactions/define/transaction_request.go +++ b/x/identities/transactions/define/transaction_request.go @@ -76,23 +76,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/identities/transactions/define/transaction_request_test.go b/x/identities/transactions/define/transaction_request_test.go index fd99eabea..674f8f314 100644 --- a/x/identities/transactions/define/transaction_request_test.go +++ b/x/identities/transactions/define/transaction_request_test.go @@ -220,11 +220,11 @@ func Test_transactionRequest_MakeMsg(t *testing.T) { mutablePropertiesString := "defaultMutable1:S|defaultMutable1" immutableMetaProperties, err := base.PrototypeMetaProperty().FromString(immutableMetaPropertiesString) require.Equal(t, nil, err) - immutableProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) + immutableProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) require.Equal(t, nil, err) mutableMetaProperties, err := base.PrototypeMetaProperty().FromString(mutableMetaPropertiesString) require.Equal(t, nil, err) - mutableProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + mutableProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) require.Equal(t, nil, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" diff --git a/x/identities/transactions/deputize/message_test.go b/x/identities/transactions/deputize/message_test.go index 750eaefe4..2dfe9779d 100644 --- a/x/identities/transactions/deputize/message_test.go +++ b/x/identities/transactions/deputize/message_test.go @@ -45,7 +45,7 @@ func createTestInput(t *testing.T) (*baseIDs.IdentityID, *baseIDs.IdentityID, *b require.Nil(t, err) maintainedProperty := "maintainedProperty:S|maintainedProperty" - maintainedProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(maintainedProperty) + maintainedProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(maintainedProperty) return testFromID.(*baseIDs.IdentityID), testToID.(*baseIDs.IdentityID), testClassificationID.(*baseIDs.ClassificationID), fromAccAddress, maintainedProperties.(*baseLists.PropertyList) } diff --git a/x/identities/transactions/deputize/transaction_request.go b/x/identities/transactions/deputize/transaction_request.go index f1fc9ddae..3d66d0373 100644 --- a/x/identities/transactions/deputize/transaction_request.go +++ b/x/identities/transactions/deputize/transaction_request.go @@ -83,7 +83,7 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - maintainedProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) + maintainedProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) if err != nil { return nil, err } diff --git a/x/identities/transactions/issue/message_test.go b/x/identities/transactions/issue/message_test.go index 4bb071158..421d7dcec 100644 --- a/x/identities/transactions/issue/message_test.go +++ b/x/identities/transactions/issue/message_test.go @@ -47,19 +47,19 @@ func createTestInput(t *testing.T) (*baseIDs.IdentityID, *baseIDs.Classification require.Nil(t, err) var immutableMetaProperties lists.PropertyList - immutableMetaProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) var immutableProperties lists.PropertyList - immutableProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") + immutableProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) var mutableMetaProperties lists.PropertyList - mutableMetaProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) var mutableProperties lists.PropertyList - mutableProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") + mutableProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) return testFromID.(*baseIDs.IdentityID), testClassificationID.(*baseIDs.ClassificationID), fromAddress, fromAccAddress, toAddress, toAccAddress, immutableMetaProperties.(*baseLists.PropertyList), immutableProperties.(*baseLists.PropertyList), mutableMetaProperties.(*baseLists.PropertyList), mutableProperties.(*baseLists.PropertyList) diff --git a/x/identities/transactions/issue/transaction_request.go b/x/identities/transactions/issue/transaction_request.go index baf38c62c..8dfd699d4 100644 --- a/x/identities/transactions/issue/transaction_request.go +++ b/x/identities/transactions/issue/transaction_request.go @@ -77,23 +77,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/identities/transactions/issue/transaction_request_test.go b/x/identities/transactions/issue/transaction_request_test.go index 7818a5c08..4d90e56e1 100644 --- a/x/identities/transactions/issue/transaction_request_test.go +++ b/x/identities/transactions/issue/transaction_request_test.go @@ -35,19 +35,19 @@ func createTestInputForRequest(t *testing.T) (*codec.LegacyAmino, helpers.CLICom immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableMetaProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) require.Equal(t, nil, err) var immutableProperties lists.PropertyList - immutableProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) + immutableProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) require.Equal(t, nil, err) var mutableMetaProperties lists.PropertyList - mutableMetaProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableMetaProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) require.Equal(t, nil, err) var mutableProperties lists.PropertyList - mutableProperties, err = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + mutableProperties, err = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) require.Equal(t, nil, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" diff --git a/x/identities/transactions/update/transaction_request.go b/x/identities/transactions/update/transaction_request.go index 309c2af0c..c8382096e 100644 --- a/x/identities/transactions/update/transaction_request.go +++ b/x/identities/transactions/update/transaction_request.go @@ -72,12 +72,12 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/identities/transactions/update/transaction_request_test.go b/x/identities/transactions/update/transaction_request_test.go index 83a75b96a..f5ba3f9f1 100644 --- a/x/identities/transactions/update/transaction_request_test.go +++ b/x/identities/transactions/update/transaction_request_test.go @@ -32,9 +32,9 @@ func createTestInput(t *testing.T) (*codec.LegacyAmino, helpers.CLICommand, clie mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - mutableMetaProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableMetaProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) require.Equal(t, nil, err) - mutableProperties, err := baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + mutableProperties, err := baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) require.Equal(t, nil, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" diff --git a/x/maintainers/auxiliaries/deputize/auxiliary_keeper_test.go b/x/maintainers/auxiliaries/deputize/auxiliary_keeper_test.go index 7776e82a7..ff4c6ef20 100644 --- a/x/maintainers/auxiliaries/deputize/auxiliary_keeper_test.go +++ b/x/maintainers/auxiliaries/deputize/auxiliary_keeper_test.go @@ -44,7 +44,7 @@ var ( testClassificationID = baseIDs.NewClassificationID(immutables, mutables) testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) maintainedProperty = "maintainedProperty:S|maintainedProperty" - maintainedProperties, _ = base.PrototypePropertyList().FromMetaPropertiesString(maintainedProperty) + maintainedProperties, _ = base.NewPropertyList().FromMetaPropertiesString(maintainedProperty) permissions = maintainerUtilities.SetModulePermissions(true, true, true) ) diff --git a/x/maintainers/auxiliaries/revoke/auxiliary_keeper_test.go b/x/maintainers/auxiliaries/revoke/auxiliary_keeper_test.go index 9fe398452..a8b8cae1c 100644 --- a/x/maintainers/auxiliaries/revoke/auxiliary_keeper_test.go +++ b/x/maintainers/auxiliaries/revoke/auxiliary_keeper_test.go @@ -42,7 +42,7 @@ var ( testClassificationID = baseIDs.NewClassificationID(immutables, mutables) testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) maintainedProperty = "maintainedProperty:S|maintainedProperty" - maintainedProperties, _ = base.PrototypePropertyList().FromMetaPropertiesString(maintainedProperty) + maintainedProperties, _ = base.NewPropertyList().FromMetaPropertiesString(maintainedProperty) permissions = maintainerUtilities.SetModulePermissions(true, true, true) ) diff --git a/x/orders/transactions/define/transaction_request.go b/x/orders/transactions/define/transaction_request.go index d9b8c7ab0..b0e05a577 100644 --- a/x/orders/transactions/define/transaction_request.go +++ b/x/orders/transactions/define/transaction_request.go @@ -71,23 +71,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/orders/transactions/define/transaction_request_test.go b/x/orders/transactions/define/transaction_request_test.go index 802e041f2..4982bc3eb 100644 --- a/x/orders/transactions/define/transaction_request_test.go +++ b/x/orders/transactions/define/transaction_request_test.go @@ -32,13 +32,13 @@ var ( immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString = "defaultMutable1:S|defaultMutable1" - immutableMetaPropertiesInterfaces, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableMetaPropertiesInterfaces, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) immutableMetaProperties = immutableMetaPropertiesInterfaces.(*baseLists.PropertyList) - immutablePropertiesInterfaces, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) + immutablePropertiesInterfaces, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) immutableProperties = immutablePropertiesInterfaces.(*baseLists.PropertyList) - mutableMetaPropertiesInterfaces, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableMetaPropertiesInterfaces, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) mutableMetaProperties = mutableMetaPropertiesInterfaces.(*baseLists.PropertyList) - mutablePropertiesInterfaces, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + mutablePropertiesInterfaces, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) mutableProperties = mutablePropertiesInterfaces.(*baseLists.PropertyList) immutables = base.NewImmutables(immutableProperties) mutables = base.NewMutables(mutableProperties) diff --git a/x/orders/transactions/deputize/message_test.go b/x/orders/transactions/deputize/message_test.go index e6998730d..a2a831b41 100644 --- a/x/orders/transactions/deputize/message_test.go +++ b/x/orders/transactions/deputize/message_test.go @@ -48,7 +48,7 @@ func CreateTestInputForMessage(t *testing.T) (*baseIDs.IdentityID, *baseIDs.Iden require.Nil(t, err) maintainedProperty := "maintainedProperty:S|maintainedProperty" - maintainedProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(maintainedProperty) + maintainedProperties, err := base.NewPropertyList().FromMetaPropertiesString(maintainedProperty) require.Equal(t, nil, err) testMessage := NewMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true) diff --git a/x/orders/transactions/deputize/transaction_request.go b/x/orders/transactions/deputize/transaction_request.go index 339131204..5f230fa42 100644 --- a/x/orders/transactions/deputize/transaction_request.go +++ b/x/orders/transactions/deputize/transaction_request.go @@ -79,7 +79,7 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, err } - maintainedProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) + maintainedProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MaintainedProperties) if err != nil { return nil, err } diff --git a/x/orders/transactions/deputize/transaction_request_test.go b/x/orders/transactions/deputize/transaction_request_test.go index 44375d68a..25df7dc24 100644 --- a/x/orders/transactions/deputize/transaction_request_test.go +++ b/x/orders/transactions/deputize/transaction_request_test.go @@ -35,7 +35,7 @@ var ( testClassificationID = baseIDs.NewClassificationID(immutables, mutables) testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) maintainedPropertyString = "maintainedProperty:S|maintainedProperty" - maintainedProperties, _ = base.PrototypePropertyList().FromMetaPropertiesString(maintainedPropertyString) + maintainedProperties, _ = base.NewPropertyList().FromMetaPropertiesString(maintainedPropertyString) testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} ) diff --git a/x/orders/transactions/immediate/transaction_request.go b/x/orders/transactions/immediate/transaction_request.go index acdde3fb2..a822bd927 100644 --- a/x/orders/transactions/immediate/transaction_request.go +++ b/x/orders/transactions/immediate/transaction_request.go @@ -123,23 +123,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, errorConstants.IncorrectFormat.Wrapf("taker split %s is not a valid integer", transactionRequest.TakerSplit) } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/orders/transactions/immediate/transaction_request_test.go b/x/orders/transactions/immediate/transaction_request_test.go index c925531e4..489ae461c 100644 --- a/x/orders/transactions/immediate/transaction_request_test.go +++ b/x/orders/transactions/immediate/transaction_request_test.go @@ -33,10 +33,10 @@ var ( immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString = "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) - immutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) - mutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) - mutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + immutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) + mutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) immutables = baseQualified.NewImmutables(immutableProperties) mutables = baseQualified.NewMutables(mutableProperties) testClassificationID = baseIDs.NewClassificationID(immutables, mutables).(*baseIDs.ClassificationID) diff --git a/x/orders/transactions/make/transaction_request.go b/x/orders/transactions/make/transaction_request.go index dc77a1a5f..51d3b4823 100644 --- a/x/orders/transactions/make/transaction_request.go +++ b/x/orders/transactions/make/transaction_request.go @@ -98,23 +98,23 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, errorConstants.IncorrectFormat.Wrapf("taker split %s is not a valid integer", transactionRequest.TakerSplit) } - immutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) + immutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableMetaProperties) if err != nil { return nil, err } - immutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) + immutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.ImmutableProperties) if err != nil { return nil, err } immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/orders/transactions/make/transaction_request_test.go b/x/orders/transactions/make/transaction_request_test.go index 2562c7321..b4d46460d 100644 --- a/x/orders/transactions/make/transaction_request_test.go +++ b/x/orders/transactions/make/transaction_request_test.go @@ -33,10 +33,10 @@ var ( immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString = "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) - immutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) - mutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) - mutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + immutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) + mutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) immutables = baseQualified.NewImmutables(immutableProperties) mutables = baseQualified.NewMutables(mutableProperties) testClassificationID = baseIDs.NewClassificationID(immutables, mutables).(*baseIDs.ClassificationID) diff --git a/x/orders/transactions/modify/transaction_request.go b/x/orders/transactions/modify/transaction_request.go index ee18ad145..1b8400c89 100644 --- a/x/orders/transactions/modify/transaction_request.go +++ b/x/orders/transactions/modify/transaction_request.go @@ -88,12 +88,12 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { return nil, errorConstants.IncorrectFormat.Wrapf("taker split %s is not a valid integer", transactionRequest.TakerSplit) } - mutableMetaProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) + mutableMetaProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableMetaProperties) if err != nil { return nil, err } - mutableProperties, err := base.PrototypePropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) + mutableProperties, err := base.NewPropertyList().FromMetaPropertiesString(transactionRequest.MutableProperties) if err != nil { return nil, err } diff --git a/x/orders/transactions/modify/transaction_request_test.go b/x/orders/transactions/modify/transaction_request_test.go index c8b891529..4add55986 100644 --- a/x/orders/transactions/modify/transaction_request_test.go +++ b/x/orders/transactions/modify/transaction_request_test.go @@ -32,10 +32,10 @@ var ( immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString = "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) - immutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) - mutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) - mutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + immutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) + mutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) immutables = baseQualified.NewImmutables(immutableProperties) mutables = baseQualified.NewMutables(mutableProperties) diff --git a/x/orders/transactions/put/transaction_request_test.go b/x/orders/transactions/put/transaction_request_test.go index 102bfd2cb..f37cb0a0c 100644 --- a/x/orders/transactions/put/transaction_request_test.go +++ b/x/orders/transactions/put/transaction_request_test.go @@ -33,10 +33,10 @@ var ( immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString = "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) - immutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(immutablePropertiesString) - mutableMetaProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) - mutableProperties, _ = baseLists.PrototypePropertyList().FromMetaPropertiesString(mutablePropertiesString) + immutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutableMetaPropertiesString) + immutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(immutablePropertiesString) + mutableMetaProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutableMetaPropertiesString) + mutableProperties, _ = baseLists.NewPropertyList().FromMetaPropertiesString(mutablePropertiesString) immutables = baseQualified.NewImmutables(immutableProperties) mutables = baseQualified.NewMutables(mutableProperties) testClassificationID = baseIDs.NewClassificationID(immutables, mutables).(*baseIDs.ClassificationID) From 189fe52e49a6cbebdf850876829e65acff31e115 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 15:20:10 +0530 Subject: [PATCH 33/57] refactor(wrap):Refactor error messages in ValidateBasic function Instead of directly returning the error in ValidateBasic function, the error messages are now wrapped with details for better debugging. This change mainly affects the error handling mechanism within the sdkTypes.AccAddressFromBech32, FromID.ValidateBasic, and Coins.Validate functions, and also refines the coins length error message. --- x/assets/transactions/wrap/message.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/assets/transactions/wrap/message.go b/x/assets/transactions/wrap/message.go index 4e75bd197..904b01684 100644 --- a/x/assets/transactions/wrap/message.go +++ b/x/assets/transactions/wrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if err := message.Coins.Validate(); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.InvalidRequest.Wrapf("coins length %d exceeds max length %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.InvalidRequest.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } From 1f0da68bd1f3b9e757b0649bebcce25c8ebb2210 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 15:21:37 +0530 Subject: [PATCH 34/57] test(wrap):Add advanced test cases for ValidateBasic method The update adds various new test cases to the ValidateBasic method in message_test.go. These cover scenarios like multiple coins, duplicate denom, and an excessive number of coins. New invalid request errors have been added to handle incorrect from address, from id, coin amount and coin denom. --- x/assets/transactions/wrap/message_test.go | 175 +++++++++++++++++---- 1 file changed, 145 insertions(+), 30 deletions(-) diff --git a/x/assets/transactions/wrap/message_test.go b/x/assets/transactions/wrap/message_test.go index 867ff9d2e..04f5429d6 100644 --- a/x/assets/transactions/wrap/message_test.go +++ b/x/assets/transactions/wrap/message_test.go @@ -4,6 +4,9 @@ package wrap import ( + "github.com/AssetMantle/schema/go/errors" + "github.com/AssetMantle/schema/go/errors/constants" + "github.com/tendermint/tendermint/crypto/ed25519" "reflect" "testing" @@ -15,10 +18,133 @@ import ( "github.com/AssetMantle/modules/helpers" ) -type fields struct { - From string - FromID *baseIDs.IdentityID - Coins types.Coins +var ( + testAddress = types.AccAddress(ed25519.GenPrivKey().PubKey().Address()).String() + testID = baseIDs.PrototypeIdentityID().(*baseIDs.IdentityID) + testCoins = types.NewCoins(types.NewCoin(denom, types.NewInt(100))) +) + +const ( + denom = "stake" +) + +func TestMessage_ValidateBasic(t *testing.T) { + tests := []struct { + name string + message *Message + wantErr errors.Error + }{ + { + "valid message", + &Message{ + From: testAddress, + FromID: testID, + Coins: testCoins, + }, + nil, + }, + { + "multiple coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom + "1", Amount: types.NewInt(100)}, types.Coin{Denom: denom + "2", Amount: types.NewInt(100)}}, + }, + nil, + }, + { + "duplicate denom", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(100)}, types.Coin{Denom: denom, Amount: types.NewInt(100)}}, + }, + constants.InvalidRequest, + }, + { + "too many coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{ + types.Coin{Denom: denom, Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "01", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "02", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "03", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "04", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "05", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "06", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "07", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "08", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "09", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "10", Amount: types.NewInt(100)}, + }, + }, + constants.InvalidRequest, + }, + { + "unsorted coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{ + types.Coin{Denom: denom + "1", Amount: types.NewInt(100)}, + types.Coin{Denom: denom, Amount: types.NewInt(100)}, + }, + }, + constants.InvalidRequest, + }, + { + "empty message", + &Message{}, + constants.InvalidRequest, + }, + { + "invalid from address", + &Message{ + From: "invalid", + FromID: testID, + Coins: testCoins, + }, + constants.InvalidRequest, + }, + { + name: "invalid from id", + message: &Message{ + From: testAddress, + FromID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, + Coins: testCoins, + }, + wantErr: constants.InvalidRequest, + }, + { + name: "invalid coin amount", + message: &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(-100)}}, + }, + wantErr: constants.InvalidRequest, + }, + { + name: "invalid coin denom", + message: &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: "", Amount: types.NewInt(100)}}, + }, + wantErr: constants.InvalidRequest, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.message.ValidateBasic() + + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("\n got: \n %v \n want: \n %v", err, tt.wantErr) + } + }) + } } func Test_messageFromInterface(t *testing.T) { @@ -58,7 +184,11 @@ func Test_messagePrototype(t *testing.T) { } func Test_message_GetSigners(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } tests := []struct { name string fields fields @@ -81,7 +211,11 @@ func Test_message_GetSigners(t *testing.T) { } func Test_message_RegisterCodec(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } type args struct { legacyAmino *codec.LegacyAmino } @@ -105,7 +239,11 @@ func Test_message_RegisterCodec(t *testing.T) { } func Test_message_Type(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } tests := []struct { name string fields fields @@ -127,29 +265,6 @@ func Test_message_Type(t *testing.T) { } } -func Test_message_ValidateBasic(t *testing.T) { - - tests := []struct { - name string - fields fields - wantErr bool - }{ - {"+ve", fields{fromAccAddress.String(), fromID, coins}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - message := &Message{ - From: tt.fields.From, - FromID: tt.fields.FromID, - Coins: tt.fields.Coins, - } - if err := message.ValidateBasic(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - func Test_NewMessage(t *testing.T) { type args struct { from types.AccAddress From 32636338d2322bc914b2f86df3620db5a8fea1c5 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 15:35:55 +0530 Subject: [PATCH 35/57] refactor(wrap):Refactor error messages in ValidateBasic function Instead of directly returning the error in ValidateBasic function, the error messages are now wrapped with details for better debugging. This change mainly affects the error handling mechanism within the sdkTypes.AccAddressFromBech32, FromID.ValidateBasic, and Coins.Validate functions, and also refines the coins length error message. --- x/assets/transactions/unwrap/message.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/assets/transactions/unwrap/message.go b/x/assets/transactions/unwrap/message.go index 9e124f65f..416bc60a3 100644 --- a/x/assets/transactions/unwrap/message.go +++ b/x/assets/transactions/unwrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if err := message.Coins.Validate(); err != nil { - return err + return errorConstants.InvalidRequest.Wrapf(err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.InvalidRequest.Wrapf("coins length %d exceeds max length %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.InvalidRequest.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } From 0611c7c2b47ad390a6316bd8a55e2dfb80a9e603 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 15:36:06 +0530 Subject: [PATCH 36/57] test(wrap):Add advanced test cases for ValidateBasic method The update adds various new test cases to the ValidateBasic method in message_test.go. These cover scenarios like multiple coins, duplicate denom, and an excessive number of coins. New invalid request errors have been added to handle incorrect from address, from id, coin amount and coin denom. --- x/assets/transactions/unwrap/message_test.go | 194 +++++++++++++++---- 1 file changed, 153 insertions(+), 41 deletions(-) diff --git a/x/assets/transactions/unwrap/message_test.go b/x/assets/transactions/unwrap/message_test.go index 808900ff1..1f3e27ebd 100644 --- a/x/assets/transactions/unwrap/message_test.go +++ b/x/assets/transactions/unwrap/message_test.go @@ -4,23 +4,146 @@ package unwrap import ( - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/schema/go/errors" + "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" baseIDs "github.com/AssetMantle/schema/go/ids/base" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/crypto/ed25519" + "reflect" + "testing" +) - "github.com/AssetMantle/modules/helpers" +var ( + testAddress = types.AccAddress(ed25519.GenPrivKey().PubKey().Address()).String() + testID = baseIDs.PrototypeIdentityID().(*baseIDs.IdentityID) + testCoins = types.NewCoins(types.NewCoin(denom, types.NewInt(100))) ) -type fields struct { - From string - FromID *baseIDs.IdentityID - Coins sdkTypes.Coins -} +const ( + denom = "stake" +) + +func TestMessage_ValidateBasic(t *testing.T) { + tests := []struct { + name string + message *Message + wantErr errors.Error + }{ + { + "valid message", + &Message{ + From: testAddress, + FromID: testID, + Coins: testCoins, + }, + nil, + }, + { + "multiple coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom + "1", Amount: types.NewInt(100)}, types.Coin{Denom: denom + "2", Amount: types.NewInt(100)}}, + }, + nil, + }, + { + "duplicate denom", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(100)}, types.Coin{Denom: denom, Amount: types.NewInt(100)}}, + }, + constants.InvalidRequest, + }, + { + "too many coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{ + types.Coin{Denom: denom, Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "01", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "02", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "03", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "04", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "05", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "06", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "07", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "08", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "09", Amount: types.NewInt(100)}, + types.Coin{Denom: denom + "10", Amount: types.NewInt(100)}, + }, + }, + constants.InvalidRequest, + }, + { + "unsorted coins", + &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{ + types.Coin{Denom: denom + "1", Amount: types.NewInt(100)}, + types.Coin{Denom: denom, Amount: types.NewInt(100)}, + }, + }, + constants.InvalidRequest, + }, + { + "empty message", + &Message{}, + constants.InvalidRequest, + }, + { + "invalid from address", + &Message{ + From: "invalid", + FromID: testID, + Coins: testCoins, + }, + constants.InvalidRequest, + }, + { + name: "invalid from id", + message: &Message{ + From: testAddress, + FromID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, + Coins: testCoins, + }, + wantErr: constants.InvalidRequest, + }, + { + name: "invalid coin amount", + message: &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(-100)}}, + }, + wantErr: constants.InvalidRequest, + }, + { + name: "invalid coin denom", + message: &Message{ + From: testAddress, + FromID: testID, + Coins: types.Coins{types.Coin{Denom: "", Amount: types.NewInt(100)}}, + }, + wantErr: constants.InvalidRequest, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.message.ValidateBasic() + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("\n got: \n %v \n want: \n %v", err, tt.wantErr) + } + }) + } +} func Test_messageFromInterface(t *testing.T) { type args struct { msg helpers.Message @@ -58,13 +181,17 @@ func Test_messagePrototype(t *testing.T) { } func Test_message_GetSigners(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } tests := []struct { name string fields fields - want []sdkTypes.AccAddress + want []types.AccAddress }{ - {"+ve", fields{fromAccAddress.String(), fromID, coins}, []sdkTypes.AccAddress{fromAccAddress}}, + {"+ve", fields{fromAccAddress.String(), fromID, coins}, []types.AccAddress{fromAccAddress}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -81,7 +208,11 @@ func Test_message_GetSigners(t *testing.T) { } func Test_message_RegisterCodec(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } type args struct { legacyAmino *codec.LegacyAmino } @@ -105,7 +236,11 @@ func Test_message_RegisterCodec(t *testing.T) { } func Test_message_Type(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + Coins types.Coins + } tests := []struct { name string fields fields @@ -127,39 +262,16 @@ func Test_message_Type(t *testing.T) { } } -func Test_message_ValidateBasic(t *testing.T) { - - tests := []struct { - name string - fields fields - wantErr bool - }{ - {"+ve", fields{fromAccAddress.String(), fromID, coins}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - message := &Message{ - From: tt.fields.From, - FromID: tt.fields.FromID, - Coins: tt.fields.Coins, - } - if err := message.ValidateBasic(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - func Test_NewMessage(t *testing.T) { type args struct { - from sdkTypes.AccAddress + from types.AccAddress fromID ids.IdentityID - coins sdkTypes.Coins + coins types.Coins } tests := []struct { name string args args - want sdkTypes.Msg + want types.Msg }{ {"+ve", args{fromAccAddress, fromID, coins}, &Message{fromAccAddress.String(), fromID, coins}}, } From 30f190cdddffde783a5d7f51dc3da7fdab795ba8 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 16:11:54 +0530 Subject: [PATCH 37/57] refactor(send):Refactor error messages in ValidateBasic function Instead of directly returning the error in ValidateBasic function, the error messages are now wrapped with details for better debugging. This change mainly affects the error handling mechanism within the sdkTypes.AccAddressFromBech32, FromID.ValidateBasic, and Coins.Validate functions, and also refines the coins length error message. --- x/assets/transactions/send/message.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/x/assets/transactions/send/message.go b/x/assets/transactions/send/message.go index 5f41007a7..48cc59ee1 100644 --- a/x/assets/transactions/send/message.go +++ b/x/assets/transactions/send/message.go @@ -37,19 +37,19 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return err + return errorConstants.IncorrectMessage.Wrapf(err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return err + return errorConstants.IncorrectMessage.Wrapf(err.Error()) } if err := message.ToID.ValidateBasic(); err != nil { - return err + return errorConstants.IncorrectMessage.Wrapf(err.Error()) } if err := message.AssetID.ValidateBasic(); err != nil { - return err + return errorConstants.IncorrectMessage.Wrapf(err.Error()) } if _, err := message.GetValueAsInt(); err != nil { - return err + return errorConstants.IncorrectMessage.Wrapf(err.Error()) } return nil } From bc0888337940ca78aa53877af3dcd47208f5568e Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 16:12:35 +0530 Subject: [PATCH 38/57] test(send):Add comprehensive tests for Message validation Expanded message_test.go with various test cases that cover scenarios for validating basic Message fields, including address, ID, asset, and value. These tests ensure that the correct error handling occurs for all possible cases in the validation process. --- x/assets/transactions/send/message_test.go | 158 ++++++++++++++++----- 1 file changed, 124 insertions(+), 34 deletions(-) diff --git a/x/assets/transactions/send/message_test.go b/x/assets/transactions/send/message_test.go index ff8bd9016..9dc354705 100644 --- a/x/assets/transactions/send/message_test.go +++ b/x/assets/transactions/send/message_test.go @@ -4,6 +4,10 @@ package send import ( + "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "github.com/tendermint/tendermint/crypto/ed25519" "reflect" "testing" @@ -15,12 +19,105 @@ import ( "github.com/AssetMantle/modules/helpers" ) -type fields struct { - From string - FromID *baseIDs.IdentityID - ToID *baseIDs.IdentityID - AssetID *baseIDs.AssetID - Value types.Int +const ( + denom = "stake" +) + +var ( + testAddress = types.AccAddress(ed25519.GenPrivKey().PubKey().Address()).String() + testID = baseIDs.PrototypeIdentityID().(*baseIDs.IdentityID) + coinAsset = base.NewCoinAsset(denom) + coinAssetID = coinAsset.GetCoinAssetID().(*baseIDs.AssetID) + testValue = types.NewInt(100).String() +) + +func TestMessage_ValidateBasic(t *testing.T) { + tests := []struct { + name string + message *Message + wantErr errors.Error + }{ + { + "valid message", + &Message{ + From: testAddress, + FromID: testID, + ToID: testID, + AssetID: coinAssetID, + Value: testValue, + }, + nil, + }, + { + "empty message", + &Message{}, + errorConstants.IncorrectMessage, + }, + { + "invalid from address", + &Message{ + From: "invalid", + FromID: testID, + ToID: testID, + AssetID: coinAssetID, + Value: testValue, + }, + errorConstants.IncorrectMessage, + }, + { + "invalid from id", + &Message{ + From: testAddress, + FromID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, + ToID: testID, + AssetID: coinAssetID, + Value: testValue, + }, + errorConstants.IncorrectMessage, + }, + { + "invalid to id", + &Message{ + From: testAddress, + FromID: testID, + ToID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, + AssetID: coinAssetID, + Value: testValue, + }, + errorConstants.IncorrectMessage, + }, + { + "invalid asset id", + &Message{ + From: testAddress, + FromID: testID, + ToID: testID, + AssetID: &baseIDs.AssetID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, + Value: testValue, + }, + errorConstants.IncorrectMessage, + }, + { + "invalid value", + &Message{ + From: testAddress, + FromID: testID, + ToID: testID, + AssetID: coinAssetID, + Value: "invalid", + }, + errorConstants.IncorrectMessage, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.message.ValidateBasic() + + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("\n got: \n %v \n want: \n %v", err, tt.wantErr) + } + }) + } } func Test_messageFromInterface(t *testing.T) { @@ -60,7 +157,13 @@ func Test_messagePrototype(t *testing.T) { } func Test_message_GetSigners(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + ToID *baseIDs.IdentityID + AssetID *baseIDs.AssetID + Value types.Int + } tests := []struct { name string fields fields @@ -85,7 +188,13 @@ func Test_message_GetSigners(t *testing.T) { } func Test_message_RegisterCodec(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + ToID *baseIDs.IdentityID + AssetID *baseIDs.AssetID + Value types.Int + } type args struct { legacyAmino *codec.LegacyAmino } @@ -111,7 +220,13 @@ func Test_message_RegisterCodec(t *testing.T) { } func Test_message_Type(t *testing.T) { - + type fields struct { + From string + FromID *baseIDs.IdentityID + ToID *baseIDs.IdentityID + AssetID *baseIDs.AssetID + Value types.Int + } tests := []struct { name string fields fields @@ -135,31 +250,6 @@ func Test_message_Type(t *testing.T) { } } -func Test_message_ValidateBasic(t *testing.T) { - - tests := []struct { - name string - fields fields - wantErr bool - }{ - {"+ve", fields{fromAccAddress.String(), fromID, fromID, assetID, testRate}, false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - message := &Message{ - From: tt.fields.From, - FromID: tt.fields.FromID, - ToID: tt.fields.ToID, - AssetID: tt.fields.AssetID, - Value: tt.fields.Value.String(), - } - if err := message.ValidateBasic(); (err != nil) != tt.wantErr { - t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} - func Test_NewMessage(t *testing.T) { type args struct { from types.AccAddress From 697ad2186b008a915d8b88378795377697a043b9 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 16:18:23 +0530 Subject: [PATCH 39/57] refactor(assets):Refactor error handling in message validation This update replaces usage of generic error messages in message validation methods of wrap, unwrap, and send transactions. These have been replaced with custom errors for invalid situations such as incorrect address, invalid id, etc. This provides more clear debugging information and improves error tracking. --- x/assets/transactions/send/message.go | 12 ++++++------ x/assets/transactions/unwrap/message.go | 8 ++++---- x/assets/transactions/wrap/message.go | 8 ++++---- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/x/assets/transactions/send/message.go b/x/assets/transactions/send/message.go index 48cc59ee1..ea2ea738e 100644 --- a/x/assets/transactions/send/message.go +++ b/x/assets/transactions/send/message.go @@ -22,7 +22,7 @@ func (message *Message) GetValueAsInt() (sdkTypes.Int, error) { if !ok { return sdkTypes.ZeroInt(), errorConstants.IncorrectFormat.Wrapf("send value %s is not a valid integer", message.Value) } else if value.IsNegative() { - return sdkTypes.ZeroInt(), errorConstants.InvalidParameter.Wrapf("invalid value %s", message.Value) + return sdkTypes.ZeroInt(), errorConstants.InvalidParameter.Wrapf("send value is negative %s", message.Value) } return value, nil @@ -37,19 +37,19 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.IncorrectMessage.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.ToID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid to id %s", err.Error()) } if err := message.AssetID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid asset id %s", err.Error()) } if _, err := message.GetValueAsInt(); err != nil { - return errorConstants.IncorrectMessage.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid value %s", err.Error()) } return nil } diff --git a/x/assets/transactions/unwrap/message.go b/x/assets/transactions/unwrap/message.go index 416bc60a3..1dc83b8dd 100644 --- a/x/assets/transactions/unwrap/message.go +++ b/x/assets/transactions/unwrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.Coins.Validate(); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid coins %s", err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.InvalidRequest.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.IncorrectMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } diff --git a/x/assets/transactions/wrap/message.go b/x/assets/transactions/wrap/message.go index 904b01684..2ebeabb3b 100644 --- a/x/assets/transactions/wrap/message.go +++ b/x/assets/transactions/wrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.Coins.Validate(); err != nil { - return errorConstants.InvalidRequest.Wrapf(err.Error()) + return errorConstants.IncorrectMessage.Wrapf("invalid coins %s", err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.InvalidRequest.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.IncorrectMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } From 3864de6018eb81977d2f43e55fe3a1c9142c0c8e Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 5 Apr 2024 16:26:00 +0530 Subject: [PATCH 40/57] refactor(errors):Refactor error names from "IncorrectMessage" to "InvalidMessage" The error name "IncorrectMessage" has been refactored to "InvalidMessage" throughout the codebase to better reflect its meaning. This change affects all modules and tests where this error name is used, improving code clarity and consistency. --- helpers/base/module.go | 4 ++-- utilities/wasm/custom_encoder.go | 4 ++-- x/assets/transactions/send/message.go | 10 +++++----- x/assets/transactions/send/message_test.go | 12 ++++++------ x/assets/transactions/unwrap/message.go | 8 ++++---- x/assets/transactions/unwrap/message_test.go | 16 ++++++++-------- x/assets/transactions/wrap/message.go | 8 ++++---- x/assets/transactions/wrap/message_test.go | 16 ++++++++-------- 8 files changed, 39 insertions(+), 39 deletions(-) diff --git a/helpers/base/module.go b/helpers/base/module.go index 50f304597..09eeb8079 100644 --- a/helpers/base/module.go +++ b/helpers/base/module.go @@ -161,7 +161,7 @@ func (module module) Route() sdkTypes.Route { return transaction.HandleMessage(sdkTypes.WrapSDKContext(context.WithEventManager(sdkTypes.NewEventManager())), message) } } - return nil, errorConstants.IncorrectMessage.Wrapf("message type %T is not supported by module %s", msg, module.Name()) + return nil, errorConstants.InvalidMessage.Wrapf("message type %T is not supported by module %s", msg, module.Name()) }) } func (module module) QuerierRoute() string { @@ -235,7 +235,7 @@ func (module module) DecodeModuleTransactionRequest(transactionName string, rawM return transaction.DecodeTransactionRequest(rawMessage) } - return nil, errorConstants.IncorrectMessage.Wrapf("transaction %s is not supported by module %s", transactionName, module.Name()) + return nil, errorConstants.InvalidMessage.Wrapf("transaction %s is not supported by module %s", transactionName, module.Name()) } func (module module) Initialize(kvStoreKey *sdkTypes.KVStoreKey, paramsSubspace paramsTypes.Subspace, auxiliaryKeepers ...interface{}) helpers.Module { module.mapper = module.mapperPrototype().Initialize(kvStoreKey) diff --git a/utilities/wasm/custom_encoder.go b/utilities/wasm/custom_encoder.go index a94aca9b4..969ca835d 100644 --- a/utilities/wasm/custom_encoder.go +++ b/utilities/wasm/custom_encoder.go @@ -21,7 +21,7 @@ func CustomEncoder(moduleList ...helpers.Module) wasm.CustomEncoder { err := json.Unmarshal(rawMessage, &wasmMessage) if err != nil { - return nil, errorConstants.IncorrectMessage.Wrapf(err.Error()) + return nil, errorConstants.InvalidMessage.Wrapf(err.Error()) } path := strings.Split(wasmMessage.GetType(), "/") @@ -37,6 +37,6 @@ func CustomEncoder(moduleList ...helpers.Module) wasm.CustomEncoder { } } - return nil, errorConstants.IncorrectMessage.Wrapf("module not found") + return nil, errorConstants.InvalidMessage.Wrapf("module not found") } } diff --git a/x/assets/transactions/send/message.go b/x/assets/transactions/send/message.go index ea2ea738e..80f44966c 100644 --- a/x/assets/transactions/send/message.go +++ b/x/assets/transactions/send/message.go @@ -37,19 +37,19 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.ToID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid to id %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid to id %s", err.Error()) } if err := message.AssetID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid asset id %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid asset id %s", err.Error()) } if _, err := message.GetValueAsInt(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid value %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid value %s", err.Error()) } return nil } diff --git a/x/assets/transactions/send/message_test.go b/x/assets/transactions/send/message_test.go index 9dc354705..454a14cd2 100644 --- a/x/assets/transactions/send/message_test.go +++ b/x/assets/transactions/send/message_test.go @@ -51,7 +51,7 @@ func TestMessage_ValidateBasic(t *testing.T) { { "empty message", &Message{}, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, { "invalid from address", @@ -62,7 +62,7 @@ func TestMessage_ValidateBasic(t *testing.T) { AssetID: coinAssetID, Value: testValue, }, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, { "invalid from id", @@ -73,7 +73,7 @@ func TestMessage_ValidateBasic(t *testing.T) { AssetID: coinAssetID, Value: testValue, }, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, { "invalid to id", @@ -84,7 +84,7 @@ func TestMessage_ValidateBasic(t *testing.T) { AssetID: coinAssetID, Value: testValue, }, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, { "invalid asset id", @@ -95,7 +95,7 @@ func TestMessage_ValidateBasic(t *testing.T) { AssetID: &baseIDs.AssetID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, Value: testValue, }, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, { "invalid value", @@ -106,7 +106,7 @@ func TestMessage_ValidateBasic(t *testing.T) { AssetID: coinAssetID, Value: "invalid", }, - errorConstants.IncorrectMessage, + errorConstants.InvalidMessage, }, } for _, tt := range tests { diff --git a/x/assets/transactions/unwrap/message.go b/x/assets/transactions/unwrap/message.go index 1dc83b8dd..4fd9ca483 100644 --- a/x/assets/transactions/unwrap/message.go +++ b/x/assets/transactions/unwrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.Coins.Validate(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid coins %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid coins %s", err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.IncorrectMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.InvalidMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } diff --git a/x/assets/transactions/unwrap/message_test.go b/x/assets/transactions/unwrap/message_test.go index 1f3e27ebd..a14f8d468 100644 --- a/x/assets/transactions/unwrap/message_test.go +++ b/x/assets/transactions/unwrap/message_test.go @@ -57,7 +57,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(100)}, types.Coin{Denom: denom, Amount: types.NewInt(100)}}, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "too many coins", @@ -78,7 +78,7 @@ func TestMessage_ValidateBasic(t *testing.T) { types.Coin{Denom: denom + "10", Amount: types.NewInt(100)}, }, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "unsorted coins", @@ -90,12 +90,12 @@ func TestMessage_ValidateBasic(t *testing.T) { types.Coin{Denom: denom, Amount: types.NewInt(100)}, }, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "empty message", &Message{}, - constants.InvalidRequest, + constants.InvalidMessage, }, { "invalid from address", @@ -104,7 +104,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: testCoins, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { name: "invalid from id", @@ -113,7 +113,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, Coins: testCoins, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, { name: "invalid coin amount", @@ -122,7 +122,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(-100)}}, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, { name: "invalid coin denom", @@ -131,7 +131,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: "", Amount: types.NewInt(100)}}, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, } for _, tt := range tests { diff --git a/x/assets/transactions/wrap/message.go b/x/assets/transactions/wrap/message.go index 2ebeabb3b..ddce5d0c6 100644 --- a/x/assets/transactions/wrap/message.go +++ b/x/assets/transactions/wrap/message.go @@ -28,16 +28,16 @@ func (message *Message) GetFromAddress() sdkTypes.AccAddress { } func (message *Message) ValidateBasic() error { if _, err := sdkTypes.AccAddressFromBech32(message.From); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from address %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from address %s", err.Error()) } if err := message.FromID.ValidateBasic(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid from id %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid from id %s", err.Error()) } if err := message.Coins.Validate(); err != nil { - return errorConstants.IncorrectMessage.Wrapf("invalid coins %s", err.Error()) + return errorConstants.InvalidMessage.Wrapf("invalid coins %s", err.Error()) } if message.Coins.Len() > constants.MaxListLength { - return errorConstants.IncorrectMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) + return errorConstants.InvalidMessage.Wrapf("number of coins in message: %d exceeds maximum allowed: %d", message.Coins.Len(), constants.MaxListLength) } return nil } diff --git a/x/assets/transactions/wrap/message_test.go b/x/assets/transactions/wrap/message_test.go index 04f5429d6..02697b02e 100644 --- a/x/assets/transactions/wrap/message_test.go +++ b/x/assets/transactions/wrap/message_test.go @@ -59,7 +59,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(100)}, types.Coin{Denom: denom, Amount: types.NewInt(100)}}, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "too many coins", @@ -80,7 +80,7 @@ func TestMessage_ValidateBasic(t *testing.T) { types.Coin{Denom: denom + "10", Amount: types.NewInt(100)}, }, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "unsorted coins", @@ -92,12 +92,12 @@ func TestMessage_ValidateBasic(t *testing.T) { types.Coin{Denom: denom, Amount: types.NewInt(100)}, }, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { "empty message", &Message{}, - constants.InvalidRequest, + constants.InvalidMessage, }, { "invalid from address", @@ -106,7 +106,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: testCoins, }, - constants.InvalidRequest, + constants.InvalidMessage, }, { name: "invalid from id", @@ -115,7 +115,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte{1, 2, 3, 4}}}, Coins: testCoins, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, { name: "invalid coin amount", @@ -124,7 +124,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: denom, Amount: types.NewInt(-100)}}, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, { name: "invalid coin denom", @@ -133,7 +133,7 @@ func TestMessage_ValidateBasic(t *testing.T) { FromID: testID, Coins: types.Coins{types.Coin{Denom: "", Amount: types.NewInt(100)}}, }, - wantErr: constants.InvalidRequest, + wantErr: constants.InvalidMessage, }, } for _, tt := range tests { From 1c1731ec079889b30b0a4300d3871377a5c80b76 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:22:14 +0530 Subject: [PATCH 41/57] chore(split/utilities): removing unnecessary checks, improving error message --- x/splits/utilities/split.go | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/x/splits/utilities/split.go b/x/splits/utilities/split.go index e3323ffd4..328dfb228 100644 --- a/x/splits/utilities/split.go +++ b/x/splits/utilities/split.go @@ -17,10 +17,6 @@ import ( ) func AddSplits(splits helpers.Collection, ownerID ids.IdentityID, assetID ids.AssetID, value sdkTypes.Int) (helpers.Collection, error) { - if value.LTE(sdkTypes.ZeroInt()) { - return nil, errorConstants.InvalidRequest.Wrapf("value must be greater than zero") - } - splitID := baseIDs.NewSplitID(assetID, ownerID) Mappable := splits.Fetch(key.NewKey(splitID)).GetMappable(key.NewKey(splitID)) @@ -34,10 +30,6 @@ func AddSplits(splits helpers.Collection, ownerID ids.IdentityID, assetID ids.As } func SubtractSplits(splits helpers.Collection, ownerID ids.IdentityID, assetID ids.AssetID, value sdkTypes.Int) (helpers.Collection, error) { - if value.LTE(sdkTypes.ZeroInt()) { - return nil, errorConstants.InvalidRequest.Wrapf("value must be greater than zero") - } - splitID := baseIDs.NewSplitID(assetID, ownerID) Mappable := splits.Fetch(key.NewKey(splitID)).GetMappable(key.NewKey(splitID)) @@ -48,7 +40,7 @@ func SubtractSplits(splits helpers.Collection, ownerID ids.IdentityID, assetID i switch split = split.Subtract(value); { case split.GetValue().LT(sdkTypes.ZeroInt()): - return nil, errorConstants.InvalidRequest.Wrapf("split value cannot be negative") + return nil, errorConstants.InsufficientBalance.Wrapf("%d is less then %d", split.GetValue(), value) case split.GetValue().Equal(sdkTypes.ZeroInt()): splits.Remove(record.NewRecord(splitID, split)) default: From 03f6a2282262aaf1ef4411df825efb47195c27cf Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:22:56 +0530 Subject: [PATCH 42/57] fix(split/mappable): adding nil checks --- x/splits/mappable/mappable.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/x/splits/mappable/mappable.go b/x/splits/mappable/mappable.go index fade962a6..c3d13ac26 100644 --- a/x/splits/mappable/mappable.go +++ b/x/splits/mappable/mappable.go @@ -30,6 +30,9 @@ func Prototype() helpers.Mappable { } func GetSplit(mappable helpers.Mappable) types.Split { + if mappable == nil || mappable.(*Mappable).Split == nil { + return nil + } return mappable.(*Mappable).Split } From e3c4347ecd7425f0e1ecc70376ea6ab66994605d Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:23:31 +0530 Subject: [PATCH 43/57] chore(splits/send): minor code optimization --- .../transactions/send/transaction_keeper_test.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/x/assets/transactions/send/transaction_keeper_test.go b/x/assets/transactions/send/transaction_keeper_test.go index df5edb4ae..24d733fd6 100644 --- a/x/assets/transactions/send/transaction_keeper_test.go +++ b/x/assets/transactions/send/transaction_keeper_test.go @@ -166,13 +166,14 @@ var ( TransactionKeeper = transactionKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager, authenticateAuxiliary, supplementAuxiliaryAuxiliary, transferAuxiliaryAuxiliary} - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(asset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(supplementAuxiliaryFailureAsset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(transferAuxiliaryFailureAsset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(immutableLockAsset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(mutableLockAsset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(mesaLockAsset)) - _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).Add(record.NewRecord(unrevealedLockAsset)) + _ = TransactionKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(asset)). + Add(record.NewRecord(supplementAuxiliaryFailureAsset)). + Add(record.NewRecord(transferAuxiliaryFailureAsset)). + Add(record.NewRecord(immutableLockAsset)). + Add(record.NewRecord(mutableLockAsset)). + Add(record.NewRecord(mesaLockAsset)). + Add(record.NewRecord(unrevealedLockAsset)) ) func TestTransactionKeeperTransact(t *testing.T) { From 185f27807692b81d042186d044da4666c4019fb9 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:25:46 +0530 Subject: [PATCH 44/57] fix(splits/transfer):Update validation in transfer auxiliaryRequest The validation in transfer's auxiliaryRequest struct has been updated to use ValidateBasic() function rather than using govalidator. This change provides a more specific validation ensuring the IDs are valid and the value is greater than zero. --- .../auxiliaries/transfer/auxiliary_request.go | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/x/splits/auxiliaries/transfer/auxiliary_request.go b/x/splits/auxiliaries/transfer/auxiliary_request.go index 8222e1080..c845eb4b1 100644 --- a/x/splits/auxiliaries/transfer/auxiliary_request.go +++ b/x/splits/auxiliaries/transfer/auxiliary_request.go @@ -4,34 +4,40 @@ package transfer import ( + "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" - "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/AssetMantle/modules/helpers" ) type auxiliaryRequest struct { - FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` - ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` - AssetID ids.AssetID `json:"assetID" valid:"required~required field assetID missing"` - Value sdkTypes.Int `json:"value" valid:"required~required field value missing"` + FromID ids.IdentityID + ToID ids.IdentityID + AssetID ids.AssetID + Value sdkTypes.Int } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) func (auxiliaryRequest auxiliaryRequest) Validate() error { - _, err := govalidator.ValidateStruct(auxiliaryRequest) - return err -} + if err := auxiliaryRequest.FromID.ValidateBasic(); err != nil { + return constants.InvalidRequest.Wrapf("invalid from ID: %s", err) + } + + if err := auxiliaryRequest.ToID.ValidateBasic(); err != nil { + return constants.InvalidRequest.Wrapf("invalid to ID: %s", err) + } -func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { - switch value := request.(type) { - case auxiliaryRequest: - return value - default: - return auxiliaryRequest{} + if err := auxiliaryRequest.AssetID.ValidateBasic(); err != nil { + return constants.InvalidRequest.Wrapf("invalid asset ID: %s", err) } + + if auxiliaryRequest.Value.LTE(sdkTypes.ZeroInt()) { + return constants.InvalidRequest.Wrapf("value must be greater than zero") + } + + return nil } func NewAuxiliaryRequest(fromID ids.IdentityID, toID ids.IdentityID, assetID ids.AssetID, value sdkTypes.Int) helpers.AuxiliaryRequest { From fee15456c4f29c13fe77450ce4e415697a37af06 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:26:20 +0530 Subject: [PATCH 45/57] refactor(splits/transfer): minor code optimizations --- .../auxiliaries/transfer/auxiliary_keeper.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/x/splits/auxiliaries/transfer/auxiliary_keeper.go b/x/splits/auxiliaries/transfer/auxiliary_keeper.go index c0b4cd6be..d7b7b9b4c 100644 --- a/x/splits/auxiliaries/transfer/auxiliary_keeper.go +++ b/x/splits/auxiliaries/transfer/auxiliary_keeper.go @@ -5,6 +5,7 @@ package transfer import ( "context" + "reflect" "github.com/AssetMantle/schema/go/data" errorConstants "github.com/AssetMantle/schema/go/errors/constants" @@ -21,21 +22,28 @@ type auxiliaryKeeper struct { var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) -func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { +func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, AuxiliaryRequest helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + if err := AuxiliaryRequest.Validate(); err != nil { + return nil, err + } + + auxiliaryRequest, ok := AuxiliaryRequest.(auxiliaryRequest) + if !ok { + return nil, errorConstants.InvalidRequest.Wrapf("invalid request type: %s", reflect.TypeOf(AuxiliaryRequest).String()) + } + if !auxiliaryKeeper.parameterManager.Fetch(context).GetParameter(propertyConstants.TransferEnabledProperty.GetID()).GetMetaProperty().GetData().Get().(data.BooleanData).Get() { return nil, errorConstants.NotAuthorized.Wrapf("transfer is not enabled") } - auxiliaryRequest := auxiliaryRequestFromInterface(request) - splits := auxiliaryKeeper.mapper.NewCollection(context) if _, err := utilities.SubtractSplits(splits, auxiliaryRequest.FromID, auxiliaryRequest.AssetID, auxiliaryRequest.Value); err != nil { - return newAuxiliaryResponse(), err + return nil, err } if _, err := utilities.AddSplits(splits, auxiliaryRequest.ToID, auxiliaryRequest.AssetID, auxiliaryRequest.Value); err != nil { - return newAuxiliaryResponse(), err + return nil, err } return newAuxiliaryResponse(), nil From fef5214c0d79bc6922157b7dfdb9ab765ab00786 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:27:01 +0530 Subject: [PATCH 46/57] test(splits/transfer): removing old test cases --- .../transfer/auxiliary_request_test.go | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/x/splits/auxiliaries/transfer/auxiliary_request_test.go b/x/splits/auxiliaries/transfer/auxiliary_request_test.go index f57a4728c..bcc728fd6 100644 --- a/x/splits/auxiliaries/transfer/auxiliary_request_test.go +++ b/x/splits/auxiliaries/transfer/auxiliary_request_test.go @@ -54,27 +54,6 @@ func TestNewAuxiliaryRequest(t *testing.T) { } } -func Test_auxiliaryRequestFromInterface(t *testing.T) { - testOwnerID, testAssetID, testValue := createTestInput1() - type args struct { - request helpers.AuxiliaryRequest - } - tests := []struct { - name string - args args - want auxiliaryRequest - }{ - {"+ve", args{NewAuxiliaryRequest(testOwnerID, testOwnerID, testAssetID, testValue)}, auxiliaryRequest{testOwnerID, testOwnerID, testAssetID, testValue}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { - t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) - } - }) - } -} - func Test_auxiliaryRequest_Validate(t *testing.T) { testOwnerID, testAssetID, testValue := createTestInput1() type fields struct { From 5e180ef53b3e994e0c2452f85a05ae55b5f50f03 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:27:50 +0530 Subject: [PATCH 47/57] test(splits/transfer): improving test coverage for keeper --- .../transfer/auxiliary_keeper_test.go | 354 ++++++++++++------ 1 file changed, 233 insertions(+), 121 deletions(-) diff --git a/x/splits/auxiliaries/transfer/auxiliary_keeper_test.go b/x/splits/auxiliaries/transfer/auxiliary_keeper_test.go index 8b6f4130a..2cde586ad 100644 --- a/x/splits/auxiliaries/transfer/auxiliary_keeper_test.go +++ b/x/splits/auxiliaries/transfer/auxiliary_keeper_test.go @@ -5,162 +5,274 @@ package transfer import ( "context" - "fmt" - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/splits/constants" + "github.com/AssetMantle/modules/x/splits/key" + "github.com/AssetMantle/modules/x/splits/mappable" + "github.com/AssetMantle/modules/x/splits/mapper" + "github.com/AssetMantle/modules/x/splits/parameters" + "github.com/AssetMantle/modules/x/splits/parameters/transfer_enabled" + "github.com/AssetMantle/modules/x/splits/record" baseData "github.com/AssetMantle/schema/go/data/base" + "github.com/AssetMantle/schema/go/documents" "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" baseIDs "github.com/AssetMantle/schema/go/ids/base" baseLists "github.com/AssetMantle/schema/go/lists/base" + baseParameters "github.com/AssetMantle/schema/go/parameters/base" baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" + "github.com/AssetMantle/schema/go/types" baseTypes "github.com/AssetMantle/schema/go/types/base" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/stretchr/testify/require" + paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/stretchr/testify/mock" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" - - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/splits/mapper" - "github.com/AssetMantle/modules/x/splits/parameters" - "github.com/AssetMantle/modules/x/splits/record" + "math/rand" + "reflect" + "testing" ) -type TestKeepers struct { - TransferKeeper helpers.AuxiliaryKeeper +type MockAuxiliary struct { + mock.Mock } -func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.ParameterManager) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - keepers := TestKeepers{ - TransferKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.AuxiliaryKeeper), - } +var _ helpers.Auxiliary = (*MockAuxiliary)(nil) - return Context, keepers, Mapper, parameterManager +func (mockAuxiliary *MockAuxiliary) GetName() string { panic(mockAuxiliary) } +func (mockAuxiliary *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := mockAuxiliary.Called() + return args.Get(0).(helpers.AuxiliaryKeeper) +} +func (mockAuxiliary *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + panic(mockAuxiliary) } -func Test_auxiliaryKeeper_Help(t *testing.T) { - Context, keepers, Mapper, parameterManager := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) - testAssetID := base.NewCoinAsset("OwnerID").GetCoinAssetID() - testRate := sdkTypes.OneInt() - split := baseTypes.NewSplit(testRate) - keepers.TransferKeeper.(auxiliaryKeeper).mapper.NewCollection(Context.Context()).Add(record.NewRecord(baseIDs.NewSplitID(testAssetID, testOwnerIdentityID), split)) - - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - } - type args struct { - context context.Context - request helpers.AuxiliaryRequest +type MockAuxiliaryKeeper struct { + mock.Mock +} + +var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) + +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := mockAuxiliaryKeeper.Called(context, request) + return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) +} +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := mockAuxiliaryKeeper.Called(m2, manager, i) + return args.Get(0).(helpers.Keeper) +} + +// mockAuxiliaryRequest +type mockAuxiliaryRequest struct { +} + +func (mockAuxiliaryRequest) Validate() error { + return nil +} + +var _ helpers.AuxiliaryRequest = (*mockAuxiliaryRequest)(nil) + +const ( + ChainID = "testChain" + Denom = "stake" + GenesisSupply = 1000000000 +) + +var ( + testSendAmount = sdkTypes.NewInt(100) + + testFromIdentity = base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()) + testFromIdentityID = testFromIdentity.(documents.NameIdentity).GetNameIdentityID() + + testToIdentity = base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()) + testToIdentityID = testToIdentity.(documents.NameIdentity).GetNameIdentityID() + + testCoinAsset = base.NewCoinAsset(Denom) + testCoinAssetID = testCoinAsset.GetCoinAssetID() + + uninitializedCoinAsset = base.NewCoinAsset("uninitialized") + uninitializedCoinAssetID = uninitializedCoinAsset.GetCoinAssetID() + + encodingConfig = simapp.MakeTestEncodingConfig() + + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) + + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) + AuxiliaryKeeper = auxiliaryKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager} + + setContext = func() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) + } + + Context = setContext() + + parameterManager = parameters.Prototype().Initialize(ParamsKeeper.Subspace(constants.ModuleName).WithKeyTable(parameters.Prototype().GetKeyTable())). + Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(baseParameters.NewParameter(baseProperties.NewMetaProperty(transfer_enabled.ID, baseData.NewBooleanData(true))))) + + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID), baseTypes.NewSplit(sdkTypes.NewInt(GenesisSupply)))) +) + +func Test_auxiliaryKeeper_Help(t *testing.T) { tests := []struct { name string - fields fields - args args + setup func() + request helpers.AuxiliaryRequest want helpers.AuxiliaryResponse - wantErr bool + wantErr errors.Error }{ - {"+ve", fields{Mapper, parameterManager}, args{Context.Context(), NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, testAssetID, testRate)}, newAuxiliaryResponse(), false}, - {"+ve Not Authorized", fields{Mapper, parameterManager}, args{Context.Context(), NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, testAssetID, sdkTypes.ZeroInt())}, newAuxiliaryResponse(), false}, - {"+ve Entity Not Found", fields{Mapper, parameterManager}, args{Context.Context(), NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, base.NewCoinAsset("test").GetCoinAssetID(), testRate)}, newAuxiliaryResponse(), false}, + { + "valid request", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, testSendAmount), + newAuxiliaryResponse(), + nil, + }, + { + "split not present", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, uninitializedCoinAssetID, testSendAmount), + nil, + errorConstants.EntityNotFound, + }, + { + "insufficient balance", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, sdkTypes.NewInt(GenesisSupply+1)), + nil, + errorConstants.InsufficientBalance, + }, + { + "send zero", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, sdkTypes.ZeroInt()), + nil, + errorConstants.InvalidRequest, + }, + { + "send negative", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, sdkTypes.NewInt(-1)), + nil, + errorConstants.InvalidRequest, + }, + { + "invalid from identity", + func() {}, + NewAuxiliaryRequest(&baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, testToIdentityID, testCoinAssetID, testSendAmount), + nil, + errorConstants.InvalidRequest, + }, + { + "invalid to identity", + func() {}, + NewAuxiliaryRequest(testFromIdentityID, &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, testCoinAssetID, testSendAmount), + nil, + errorConstants.InvalidRequest, + }, + { + "invalid request type", + func() {}, + mockAuxiliaryRequest{}, + nil, + errorConstants.InvalidRequest, + }, + { + "with many splits", + func() { + for i := 0; i < 100000; i++ { + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(baseIDs.NewSplitID(base.NewCoinAsset(random.GenerateUniqueIdentifier()).GetCoinAssetID(), base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()).GetNameIdentityID()), baseTypes.NewSplit(sdkTypes.NewInt(int64(rand.Intn(100000000000)))))) + } + }, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, testSendAmount), + newAuxiliaryResponse(), + nil, + }, + { + "transfer full amount", + func() { + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Remove(record.NewRecord(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID), baseTypes.NewSplit(sdkTypes.OneInt()))). + Add(record.NewRecord(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID), baseTypes.NewSplit(sdkTypes.NewInt(GenesisSupply)))) + }, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, sdkTypes.NewInt(GenesisSupply)), + newAuxiliaryResponse(), + nil, + }, + { + "transfer not enabled", + func() { + parameterManager.Set(sdkTypes.WrapSDKContext(Context), baseLists.NewParameterList(baseParameters.NewParameter(baseProperties.NewMetaProperty(transfer_enabled.ID, baseData.NewBooleanData(false))))) + }, + NewAuxiliaryRequest(testFromIdentityID, testToIdentityID, testCoinAssetID, testSendAmount), + nil, + errorConstants.NotAuthorized, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - auxiliaryKeeper := auxiliaryKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - } - got, err := auxiliaryKeeper.Help(tt.args.context, tt.args.request) - if (err != nil) != tt.wantErr { - t.Errorf("Help() error = %v, wantErr %v", err, tt.wantErr) - return + tt.setup() + + var fromSplitBefore, toSplitBefore types.Split + if tt.wantErr == nil { + fromSplitBefore = mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(tt.request.(auxiliaryRequest).AssetID, tt.request.(auxiliaryRequest).FromID))).GetMappable()) + toSplitBefore = mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(tt.request.(auxiliaryRequest).AssetID, tt.request.(auxiliaryRequest).ToID))).GetMappable()) } + + got, err := AuxiliaryKeeper.Help(sdkTypes.WrapSDKContext(Context), tt.request) + if !reflect.DeepEqual(got, tt.want) { t.Errorf("Help() got = %v, want %v", got, tt.want) } - }) - } -} -func Test_auxiliaryKeeper_Initialize(t *testing.T) { - _, _, Mapper, parameterManager := createTestInput(t) - type fields struct { - mapper helpers.Mapper - } - type args struct { - mapper helpers.Mapper - in1 helpers.ParameterManager - in2 []interface{} - } - tests := []struct { - name string - fields fields - args args - want helpers.Keeper - }{ - {"+ve", fields{Mapper}, args{Mapper, parameterManager, []interface{}{}}, auxiliaryKeeper{Mapper, parameterManager}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - au := auxiliaryKeeper{ - mapper: tt.fields.mapper, + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("Help() err = %v, wantErr %v", err, tt.wantErr) } - if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) - } - }) - } -} -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.AuxiliaryKeeper - }{ - {"+ve", auxiliaryKeeper{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + if tt.wantErr == nil { + fromSplitAfter := mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(tt.request.(auxiliaryRequest).AssetID, tt.request.(auxiliaryRequest).FromID))).GetMappable()) + toSplitAfter := mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(tt.request.(auxiliaryRequest).AssetID, tt.request.(auxiliaryRequest).ToID))).GetMappable()) + + if toSplitAfter == nil { + t.Errorf("to split not created") + } + + if fromSplitBefore == nil { + t.Errorf("from split was not present") + } + + if fromSplitAfter == nil { + if !fromSplitBefore.GetValue().Equal(tt.request.(auxiliaryRequest).Value) { + t.Errorf("from split incorrectly deleted") + } + } else if !fromSplitBefore.GetValue().Sub(tt.request.(auxiliaryRequest).Value).Equal(fromSplitAfter.GetValue()) { + t.Errorf("from split not updated") + } + + if toSplitBefore == nil { + if !toSplitAfter.GetValue().Equal(tt.request.(auxiliaryRequest).Value) { + t.Errorf("to split incorrectly created") + } + } else if !toSplitBefore.GetValue().Add(tt.request.(auxiliaryRequest).Value).Equal(toSplitAfter.GetValue()) { + t.Errorf("to split not updated") + } } }) } From 3a88281b889ff8c1ea54ed95039e0276c5101ca9 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 16:29:03 +0530 Subject: [PATCH 48/57] test(identities/authenticate): improving test coverage for keeper --- .../authenticate/auxiliary_keeper_test.go | 274 +++++++++--------- 1 file changed, 137 insertions(+), 137 deletions(-) diff --git a/x/identities/auxiliaries/authenticate/auxiliary_keeper_test.go b/x/identities/auxiliaries/authenticate/auxiliary_keeper_test.go index bfe650872..2861cd093 100644 --- a/x/identities/auxiliaries/authenticate/auxiliary_keeper_test.go +++ b/x/identities/auxiliaries/authenticate/auxiliary_keeper_test.go @@ -5,173 +5,173 @@ package authenticate import ( "context" - "fmt" - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/identities/constants" + "github.com/AssetMantle/modules/x/identities/mapper" + "github.com/AssetMantle/modules/x/identities/parameters" + "github.com/AssetMantle/modules/x/identities/record" baseData "github.com/AssetMantle/schema/go/data/base" - baseDocuments "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/documents" + "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/stretchr/testify/require" + paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/stretchr/testify/mock" + "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "reflect" + "testing" +) - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/identities/mapper" - "github.com/AssetMantle/modules/x/identities/parameters" - "github.com/AssetMantle/modules/x/identities/record" - "github.com/AssetMantle/modules/x/metas/auxiliaries/supplement" +type MockAuxiliary struct { + mock.Mock +} + +var _ helpers.Auxiliary = (*MockAuxiliary)(nil) + +func (mockAuxiliary *MockAuxiliary) GetName() string { panic(mockAuxiliary) } +func (mockAuxiliary *MockAuxiliary) GetKeeper() helpers.AuxiliaryKeeper { + args := mockAuxiliary.Called() + return args.Get(0).(helpers.AuxiliaryKeeper) +} +func (mockAuxiliary *MockAuxiliary) Initialize(_ helpers.Mapper, _ helpers.ParameterManager, _ ...interface{}) helpers.Auxiliary { + panic(mockAuxiliary) +} + +type MockAuxiliaryKeeper struct { + mock.Mock +} + +var _ helpers.AuxiliaryKeeper = (*MockAuxiliaryKeeper)(nil) + +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + args := mockAuxiliaryKeeper.Called(context, request) + return args.Get(0).(helpers.AuxiliaryResponse), args.Error(1) +} +func (mockAuxiliaryKeeper *MockAuxiliaryKeeper) Initialize(m2 helpers.Mapper, manager helpers.ParameterManager, i []interface{}) helpers.Keeper { + args := mockAuxiliaryKeeper.Called(m2, manager, i) + return args.Get(0).(helpers.Keeper) +} + +const ( + ChainID = "testChain" ) var ( - supplementAuxiliary helpers.Auxiliary -) + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) -type TestKeepers struct { - AuthenticateKeeper helpers.AuxiliaryKeeper -} + supplementAuxiliaryKeeper = new(MockAuxiliaryKeeper) + _ = supplementAuxiliaryKeeper.On("Help", mock.Anything, mock.Anything).Return(newAuxiliaryResponse(), nil) + + supplementAuxiliary = new(MockAuxiliary) + _ = supplementAuxiliary.On("GetKeeper").Return(supplementAuxiliaryKeeper) + + provisionedAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + unprovisionedAddress = sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + testIdentity = base.PrototypeNameIdentity().ProvisionAddress(provisionedAddress) + testIdentityID = testIdentity.(documents.NameIdentity).GetNameIdentityID() + + paramsStoreKey = sdkTypes.NewKVStoreKey(paramsTypes.StoreKey) + paramsTransientStoreKeys = sdkTypes.NewTransientStoreKey(paramsTypes.TStoreKey) + ParamsKeeper = paramsKeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, paramsStoreKey, paramsTransientStoreKeys) + + encodingConfig = simapp.MakeTestEncodingConfig() + + parameterManager = parameters.Prototype().Initialize(ParamsKeeper.Subspace(constants.ModuleName).WithKeyTable(parameters.Prototype().GetKeyTable())) + + AuxiliaryKeeper = auxiliaryKeeper{mapper.Prototype().Initialize(moduleStoreKey), parameterManager, supplementAuxiliary} + + setContext = func() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.ParameterManager) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - supplementAuxiliary = supplement.Auxiliary.Initialize(Mapper, parameterManager) - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - keepers := TestKeepers{ - AuthenticateKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{supplementAuxiliary}).(helpers.AuxiliaryKeeper), } - return Context, keepers, Mapper, parameterManager -} + Context = setContext() + + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(testIdentity)) +) func Test_auxiliaryKeeper_Help(t *testing.T) { - Context, keepers, Mapper, parameterManager := CreateTestInput(t) - mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData())) - immutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData())) - immutables := baseQualified.NewImmutables(immutableProperties) - mutables := baseQualified.NewMutables(mutableProperties) - testClassificationID := baseIDs.NewClassificationID(immutables, mutables) - testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - testIdentity := baseDocuments.NewIdentity(testClassificationID, immutables, mutables) - testIdentity.ProvisionAddress([]sdkTypes.AccAddress{fromAccAddress}...) - keepers.AuthenticateKeeper.(auxiliaryKeeper).mapper.NewCollection(Context.Context()).Add(record.NewRecord(testIdentity)) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - supplementAuxiliary helpers.Auxiliary - } - type args struct { - context context.Context - request helpers.AuxiliaryRequest - } tests := []struct { name string - fields fields - args args + setup func() + request helpers.AuxiliaryRequest want helpers.AuxiliaryResponse - wantErr bool + wantErr errors.Error }{ - {"+ve", fields{Mapper, parameterManager, supplementAuxiliary}, args{Context.Context(), NewAuxiliaryRequest(fromAccAddress, testFromID)}, newAuxiliaryResponse(), false}, + { + "valid request", + func() {}, + auxiliaryRequest{ + Address: provisionedAddress, + IdentityID: testIdentityID, + }, + newAuxiliaryResponse(), + nil, + }, + { + "invalid request", + func() {}, + auxiliaryRequest{ + Address: unprovisionedAddress, + IdentityID: testIdentityID, + }, + nil, + errorConstants.NotAuthorized, + }, + { + "identity not found", + func() {}, + auxiliaryRequest{ + Address: provisionedAddress, + IdentityID: base.NewNameIdentity(baseIDs.NewStringID("not found"), baseData.NewListData()).GetNameIdentityID(), + }, + nil, + errorConstants.EntityNotFound, + }, + { + "many identities present", + func() { + for i := 0; i < 10000; i++ { + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData(baseData.NewAccAddressData(sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address())), baseData.NewAccAddressData(sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address())), baseData.NewAccAddressData(sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address())), baseData.NewAccAddressData(sdkTypes.AccAddress(ed25519.GenPrivKey().PubKey().Address())))))) + } + }, + auxiliaryRequest{ + Address: provisionedAddress, + IdentityID: testIdentityID, + }, + newAuxiliaryResponse(), + nil, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - auxiliaryKeeper := auxiliaryKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - supplementAuxiliary: tt.fields.supplementAuxiliary, - } - got, err := auxiliaryKeeper.Help(tt.args.context, tt.args.request) - if (err != nil) != tt.wantErr { - t.Errorf("Help() error = %v, wantErr %v", err, tt.wantErr) - return - } + tt.setup() + + got, err := AuxiliaryKeeper.Help(sdkTypes.WrapSDKContext(Context), tt.request) + if !reflect.DeepEqual(got, tt.want) { t.Errorf("Help() got = %v, want %v", got, tt.want) } - }) - } -} -func Test_auxiliaryKeeper_Initialize(t *testing.T) { - _, _, Mapper, parameterManager := CreateTestInput(t) - type fields struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - supplementAuxiliary helpers.Auxiliary - } - type args struct { - mapper helpers.Mapper - parameterManager helpers.ParameterManager - auxiliaries []interface{} - } - tests := []struct { - name string - fields fields - args args - want helpers.Keeper - }{ - {"+ve", fields{Mapper, parameterManager, supplementAuxiliary}, args{Mapper, parameterManager, []interface{}{}}, auxiliaryKeeper{Mapper, parameterManager, supplementAuxiliary}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - auxiliaryKeeper := auxiliaryKeeper{ - mapper: tt.fields.mapper, - parameterManager: tt.fields.parameterManager, - supplementAuxiliary: tt.fields.supplementAuxiliary, - } - if got := auxiliaryKeeper.Initialize(tt.args.mapper, tt.args.parameterManager, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) - } - }) - } -} -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.AuxiliaryKeeper - }{ - {"+ve", auxiliaryKeeper{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("Help() error = %v, wantErr %v", err, tt.wantErr) } }) } From a99b3397f28a0f9187d76c20e3f2db2e56d27a53 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:13:26 +0530 Subject: [PATCH 49/57] Refactor validation in mint auxiliary request The validation process in the mint auxiliary request class of the x splits module was revamped. Instead of using the 'govalidator' package for validation, each attribute is now individually validated using 'ValidateBasic' method and error messages are handled more precisely. --- .../auxiliaries/mint/auxiliary_request.go | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/x/splits/auxiliaries/mint/auxiliary_request.go b/x/splits/auxiliaries/mint/auxiliary_request.go index 5f8b3b1dc..51c765497 100644 --- a/x/splits/auxiliaries/mint/auxiliary_request.go +++ b/x/splits/auxiliaries/mint/auxiliary_request.go @@ -4,33 +4,35 @@ package mint import ( + errorConstants "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" - "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/AssetMantle/modules/helpers" ) type auxiliaryRequest struct { - OwnerID ids.IdentityID `json:"ownerID" valid:"required~required field ownerID missing"` - ids.AssetID `json:"assetID" valid:"required~required field assetId missing"` - Value sdkTypes.Int `json:"value" valid:"required~required field value missing"` + OwnerID ids.IdentityID + ids.AssetID + Value sdkTypes.Int } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) func (auxiliaryRequest auxiliaryRequest) Validate() error { - _, err := govalidator.ValidateStruct(auxiliaryRequest) - return err -} + if err := auxiliaryRequest.OwnerID.ValidateBasic(); err != nil { + return errorConstants.InvalidRequest.Wrapf("invalid owner ID: %s", err) + } -func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { - switch value := request.(type) { - case auxiliaryRequest: - return value - default: - return auxiliaryRequest{} + if err := auxiliaryRequest.AssetID.ValidateBasic(); err != nil { + return errorConstants.InvalidRequest.Wrapf("invalid asset ID: %s", err) } + + if auxiliaryRequest.Value.LTE(sdkTypes.ZeroInt()) { + return errorConstants.InvalidRequest.Wrapf("value must be greater than zero") + } + + return nil } func NewAuxiliaryRequest(ownerID ids.IdentityID, assetID ids.AssetID, value sdkTypes.Int) helpers.AuxiliaryRequest { From fef95cfd19fcf6c1527e5484b1d00e54f2bb67e9 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:13:45 +0530 Subject: [PATCH 50/57] Remove auxiliaryRequestFromInterface test The test method Test_auxiliaryRequestFromInterface has been removed from the mint auxiliary request test file in the x splits module. This change simplifies the test structure and streamlines the module by eliminating unnecessary testing of auxiliaryRequestFromInterface function. --- .../mint/auxiliary_request_test.go | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/x/splits/auxiliaries/mint/auxiliary_request_test.go b/x/splits/auxiliaries/mint/auxiliary_request_test.go index be9c32759..5378383ba 100644 --- a/x/splits/auxiliaries/mint/auxiliary_request_test.go +++ b/x/splits/auxiliaries/mint/auxiliary_request_test.go @@ -53,27 +53,6 @@ func TestNewAuxiliaryRequest(t *testing.T) { } } -func Test_auxiliaryRequestFromInterface(t *testing.T) { - testOwnerID, testAssetID, testValue := createTestInput1() - type args struct { - request helpers.AuxiliaryRequest - } - tests := []struct { - name string - args args - want auxiliaryRequest - }{ - {"+ve", args{NewAuxiliaryRequest(testOwnerID, testAssetID, testValue)}, auxiliaryRequest{testOwnerID, testAssetID, testValue}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { - t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) - } - }) - } -} - func Test_auxiliaryRequest_Validate(t *testing.T) { testOwnerID, testAssetID, testValue := createTestInput1() type fields struct { From d459f7015c78df71b5b6c396ec021096fba02d68 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:14:16 +0530 Subject: [PATCH 51/57] Update auxiliary tests in mint module Revised auxiliary tests in the mint module of the x splits package. Unnecessary test cases have been removed, including testing of auxiliaryRequestFromInterface function. Also, new test scenarios were added for improved code coverage and validity checks. The helper function "createTestInput" was removed and replaced with global variables for better readability and consistency. --- .../auxiliaries/mint/auxiliary_keeper_test.go | 257 ++++++++++-------- 1 file changed, 138 insertions(+), 119 deletions(-) diff --git a/x/splits/auxiliaries/mint/auxiliary_keeper_test.go b/x/splits/auxiliaries/mint/auxiliary_keeper_test.go index bc16ffd56..fb6a0fdf9 100644 --- a/x/splits/auxiliaries/mint/auxiliary_keeper_test.go +++ b/x/splits/auxiliaries/mint/auxiliary_keeper_test.go @@ -4,158 +4,177 @@ package mint import ( - "context" - "fmt" - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/splits/constants" + "github.com/AssetMantle/modules/x/splits/key" + "github.com/AssetMantle/modules/x/splits/mappable" + "github.com/AssetMantle/modules/x/splits/mapper" + "github.com/AssetMantle/modules/x/splits/record" baseData "github.com/AssetMantle/schema/go/data/base" + "github.com/AssetMantle/schema/go/documents" "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" + "github.com/AssetMantle/schema/go/types" baseTypes "github.com/AssetMantle/schema/go/types/base" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/mock" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "math/rand" + "reflect" + "testing" +) - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/splits/mapper" - "github.com/AssetMantle/modules/x/splits/parameters" - "github.com/AssetMantle/modules/x/splits/record" +const ( + ChainID = "testChain" + Denom = "stake" + GenesisSupply = 1000000000 ) -type TestKeepers struct { - MintKeeper helpers.AuxiliaryKeeper +type mockAuxiliaryRequest struct { + mock.Mock } -func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.ParameterManager) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - keepers := TestKeepers{ - MintKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.AuxiliaryKeeper), +func (*mockAuxiliaryRequest) Validate() error { + return nil +} + +var _ helpers.AuxiliaryRequest = (*mockAuxiliaryRequest)(nil) +var ( + testSendAmount = sdkTypes.NewInt(100) + + testFromIdentity = base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()) + testFromIdentityID = testFromIdentity.(documents.NameIdentity).GetNameIdentityID() + + testCoinAsset = base.NewCoinAsset(Denom) + testCoinAssetID = testCoinAsset.GetCoinAssetID() + + encodingConfig = simapp.MakeTestEncodingConfig() + + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) + AuxiliaryKeeper = auxiliaryKeeper{mapper.Prototype().Initialize(moduleStoreKey)} + + setContext = func() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) + } - return Context, keepers, Mapper, parameterManager -} + Context = setContext() +) func Test_auxiliaryKeeper_Help(t *testing.T) { - Context, keepers, Mapper, _ := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) - testAssetID := base.NewCoinAsset("OwnerID").GetCoinAssetID() - testRate := sdkTypes.OneInt() - split := baseTypes.NewSplit(testRate) - keepers.MintKeeper.(auxiliaryKeeper).mapper.NewCollection(Context.Context()).Add(record.NewRecord(baseIDs.NewSplitID(testAssetID, testOwnerIdentityID), split)) - type fields struct { - mapper helpers.Mapper - } - type args struct { - context context.Context - request helpers.AuxiliaryRequest - } tests := []struct { name string - fields fields - args args + setup func() + request helpers.AuxiliaryRequest want helpers.AuxiliaryResponse - wantErr bool + wantErr errors.Error }{ - {"+ve", fields{Mapper}, args{Context.Context(), NewAuxiliaryRequest(testOwnerIdentityID, testAssetID, testRate)}, newAuxiliaryResponse(), false}, + { + "valid request", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + newAuxiliaryResponse(), + nil, + }, + { + "invalid ownerID", + func() {}, + auxiliaryRequest{ + OwnerID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + nil, + errorConstants.InvalidRequest, + }, + { + "invalid assetID", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: &baseIDs.AssetID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, + Value: testSendAmount, + }, + nil, + errorConstants.InvalidRequest, + }, { + "invalid value", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: sdkTypes.NewInt(-1), + }, + nil, + errorConstants.InvalidRequest, + }, + { + "invalid request type", + func() {}, + &mockAuxiliaryRequest{}, + nil, + errorConstants.InvalidRequest, + }, + { + "with many splits", + func() { + for i := 0; i < 100000; i++ { + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(baseIDs.NewSplitID(base.NewCoinAsset(random.GenerateUniqueIdentifier()).GetCoinAssetID(), base.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()).GetNameIdentityID()), baseTypes.NewSplit(sdkTypes.NewInt(int64(rand.Intn(100000000000)))))) + } + }, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + newAuxiliaryResponse(), + nil, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - auxiliaryKeeper := auxiliaryKeeper{ - mapper: tt.fields.mapper, - } - got, err := auxiliaryKeeper.Help(tt.args.context, tt.args.request) - if (err != nil) != tt.wantErr { - t.Errorf("Help() error = %v, wantErr %v", err, tt.wantErr) - return + tt.setup() + + var splitBefore types.Split + if tt.wantErr == nil { + splitBefore = mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID))).GetMappable()) } + got, err := AuxiliaryKeeper.Help(sdkTypes.WrapSDKContext(Context), tt.request) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Help() got = %v, want %v", got, tt.want) } - }) - } -} -func Test_auxiliaryKeeper_Initialize(t *testing.T) { - _, _, Mapper, parameterManager := createTestInput(t) - type fields struct { - mapper helpers.Mapper - } - type args struct { - mapper helpers.Mapper - in1 helpers.ParameterManager - in2 []interface{} - } - tests := []struct { - name string - fields fields - args args - want helpers.Keeper - }{ - {"+ve", fields{Mapper}, args{Mapper, parameterManager, []interface{}{}}, auxiliaryKeeper{Mapper}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - au := auxiliaryKeeper{ - mapper: tt.fields.mapper, - } - if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("\n want error: \n %v \n got error: \n %v", err, tt.wantErr) } - }) - } -} -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.AuxiliaryKeeper - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + if tt.wantErr == nil { + splitAfter := mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID))).GetMappable()) + if splitBefore == nil { + if !splitAfter.GetValue().Equal(testSendAmount) { + t.Errorf("incorrect split value after minting") + } + } else { + if !splitAfter.GetValue().Sub(splitBefore.GetValue()).Equal(testSendAmount) { + t.Errorf("incorrect split value after minting") + } + } } }) } From d6d14e3652a9afdb2717e469cd723bcf2f6d4022 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:14:50 +0530 Subject: [PATCH 52/57] Improve validation and error handling in mint module Refactored the Help function in the mint module's auxiliary helper to enhance input validation and error handling. It now validates the AuxiliaryRequest explicitly and returns custom error for invalid request type. This update ensures more robust code execution and improved debugging capability. --- x/splits/auxiliaries/mint/auxiliary_keeper.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/x/splits/auxiliaries/mint/auxiliary_keeper.go b/x/splits/auxiliaries/mint/auxiliary_keeper.go index af11c9cdd..143eec497 100644 --- a/x/splits/auxiliaries/mint/auxiliary_keeper.go +++ b/x/splits/auxiliaries/mint/auxiliary_keeper.go @@ -5,6 +5,8 @@ package mint import ( "context" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "reflect" "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/splits/utilities" @@ -16,11 +18,18 @@ type auxiliaryKeeper struct { var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) -func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { - auxiliaryRequest := auxiliaryRequestFromInterface(request) +func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, AuxiliaryRequest helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { + if err := AuxiliaryRequest.Validate(); err != nil { + return nil, err + } + + auxiliaryRequest, ok := AuxiliaryRequest.(auxiliaryRequest) + if !ok { + return nil, errorConstants.InvalidRequest.Wrapf("invalid request type: %s", reflect.TypeOf(AuxiliaryRequest).String()) + } if _, err := utilities.AddSplits(auxiliaryKeeper.mapper.NewCollection(context), auxiliaryRequest.OwnerID, auxiliaryRequest.AssetID, auxiliaryRequest.Value); err != nil { - return newAuxiliaryResponse(), err + return nil, err } return newAuxiliaryResponse(), nil From f32fc84ef669af4d5443540f80425edd2888ecac Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:20:20 +0530 Subject: [PATCH 53/57] minor code cleanup --- x/splits/auxiliaries/mint/auxiliary_keeper_test.go | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/x/splits/auxiliaries/mint/auxiliary_keeper_test.go b/x/splits/auxiliaries/mint/auxiliary_keeper_test.go index fb6a0fdf9..b046814a0 100644 --- a/x/splits/auxiliaries/mint/auxiliary_keeper_test.go +++ b/x/splits/auxiliaries/mint/auxiliary_keeper_test.go @@ -19,7 +19,6 @@ import ( baseIDs "github.com/AssetMantle/schema/go/ids/base" "github.com/AssetMantle/schema/go/types" baseTypes "github.com/AssetMantle/schema/go/types/base" - "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/mock" @@ -32,9 +31,8 @@ import ( ) const ( - ChainID = "testChain" - Denom = "stake" - GenesisSupply = 1000000000 + ChainID = "testChain" + Denom = "stake" ) type mockAuxiliaryRequest struct { @@ -55,8 +53,6 @@ var ( testCoinAsset = base.NewCoinAsset(Denom) testCoinAssetID = testCoinAsset.GetCoinAssetID() - encodingConfig = simapp.MakeTestEncodingConfig() - moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) AuxiliaryKeeper = auxiliaryKeeper{mapper.Prototype().Initialize(moduleStoreKey)} From 44b61e67be4e0e4f4d1915cb321abaf5afb07065 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:35:22 +0530 Subject: [PATCH 54/57] Removed obsolete auxiliaryRequestFromInterface test This commit removes the 'Test_auxiliaryRequestFromInterface' function from the 'auxiliary_request_test.go' file. The test was deemed unnecessary and not contributing any value to the testing suite. --- .../burn/auxiliary_request_test.go | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/x/splits/auxiliaries/burn/auxiliary_request_test.go b/x/splits/auxiliaries/burn/auxiliary_request_test.go index a4d8e80d6..c82eeab8b 100644 --- a/x/splits/auxiliaries/burn/auxiliary_request_test.go +++ b/x/splits/auxiliaries/burn/auxiliary_request_test.go @@ -53,27 +53,6 @@ func TestNewAuxiliaryRequest(t *testing.T) { } } -func Test_auxiliaryRequestFromInterface(t *testing.T) { - testOwnerID, testAssetID, testValue := createTestInput1() - type args struct { - request helpers.AuxiliaryRequest - } - tests := []struct { - name string - args args - want auxiliaryRequest - }{ - {"+ve", args{NewAuxiliaryRequest(testOwnerID, testAssetID, testValue)}, auxiliaryRequest{testOwnerID, testAssetID, testValue}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { - t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) - } - }) - } -} - func Test_auxiliaryRequest_Validate(t *testing.T) { testOwnerID, testAssetID, testValue := createTestInput1() type fields struct { From ac6d5e6a5b8245977bbf51b00251ff094817b1c5 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:35:37 +0530 Subject: [PATCH 55/57] Refactor validation in auxiliaryRequest This commit replaces the govalidator usage for auxiliaryRequest validation with custom error checking. It also removes unnecessary `valid` struct tags and enhances error messages. Now validation checks for specifics: the validity of both owner ids, asset ids and makes sure that value is greater than zero. --- .../auxiliaries/burn/auxiliary_request.go | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/x/splits/auxiliaries/burn/auxiliary_request.go b/x/splits/auxiliaries/burn/auxiliary_request.go index dde34e2f5..e96839ab4 100644 --- a/x/splits/auxiliaries/burn/auxiliary_request.go +++ b/x/splits/auxiliaries/burn/auxiliary_request.go @@ -4,33 +4,35 @@ package burn import ( + errorConstants "github.com/AssetMantle/schema/go/errors/constants" "github.com/AssetMantle/schema/go/ids" - "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/AssetMantle/modules/helpers" ) type auxiliaryRequest struct { - OwnerID ids.IdentityID `json:"ownerID" valid:"required~required field ownerID missing"` - ids.AssetID `json:"assetID" valid:"required~required field assetId missing"` - Value sdkTypes.Int `json:"value" valid:"required~required field value missing"` + OwnerID ids.IdentityID + ids.AssetID + Value sdkTypes.Int } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) func (auxiliaryRequest auxiliaryRequest) Validate() error { - _, err := govalidator.ValidateStruct(auxiliaryRequest) - return err -} + if err := auxiliaryRequest.OwnerID.ValidateBasic(); err != nil { + return errorConstants.InvalidRequest.Wrapf("invalid owner ID: %s", err) + } -func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { - switch value := request.(type) { - case auxiliaryRequest: - return value - default: - return auxiliaryRequest{} + if err := auxiliaryRequest.AssetID.ValidateBasic(); err != nil { + return errorConstants.InvalidRequest.Wrapf("invalid asset ID: %s", err) } + + if auxiliaryRequest.Value.LTE(sdkTypes.ZeroInt()) { + return errorConstants.InvalidRequest.Wrapf("value must be greater than zero") + } + + return nil } func NewAuxiliaryRequest(ownerID ids.IdentityID, assetID ids.AssetID, value sdkTypes.Int) helpers.AuxiliaryRequest { From adac5167e5b312b763c0308eebc09a46e7a32d5f Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:36:01 +0530 Subject: [PATCH 56/57] Refactor auxiliaryRequest validation and tests This commit refactors the process of validation in auxiliaryRequest and its corresponding test cases. The update replaces the use of govalidator with custom error checking, removes unnecessary 'valid' struct tags, and enhances the clarity of error messages. The validation now specifically checks the validity of the owner and asset IDs, and ensures that the value is greater than zero. --- .../auxiliaries/burn/auxiliary_keeper_test.go | 269 ++++++++++-------- 1 file changed, 149 insertions(+), 120 deletions(-) diff --git a/x/splits/auxiliaries/burn/auxiliary_keeper_test.go b/x/splits/auxiliaries/burn/auxiliary_keeper_test.go index fb7dcdd9f..0cec8a2d4 100644 --- a/x/splits/auxiliaries/burn/auxiliary_keeper_test.go +++ b/x/splits/auxiliaries/burn/auxiliary_keeper_test.go @@ -4,157 +4,186 @@ package burn import ( - "context" - "fmt" - "reflect" - "testing" - + "github.com/AssetMantle/modules/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/x/splits/constants" + "github.com/AssetMantle/modules/x/splits/key" + "github.com/AssetMantle/modules/x/splits/mappable" + "github.com/AssetMantle/modules/x/splits/mapper" + "github.com/AssetMantle/modules/x/splits/record" baseData "github.com/AssetMantle/schema/go/data/base" + "github.com/AssetMantle/schema/go/documents" baseDocuments "github.com/AssetMantle/schema/go/documents/base" + "github.com/AssetMantle/schema/go/errors" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" baseIDs "github.com/AssetMantle/schema/go/ids/base" - baseLists "github.com/AssetMantle/schema/go/lists/base" - baseProperties "github.com/AssetMantle/schema/go/properties/base" - baseQualified "github.com/AssetMantle/schema/go/qualified/base" + "github.com/AssetMantle/schema/go/types" baseTypes "github.com/AssetMantle/schema/go/types/base" - "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - "github.com/stretchr/testify/require" + "github.com/stretchr/testify/mock" "github.com/tendermint/tendermint/libs/log" protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + "math/rand" + "reflect" + "testing" +) - "github.com/AssetMantle/modules/helpers" - baseHelpers "github.com/AssetMantle/modules/helpers/base" - "github.com/AssetMantle/modules/x/splits/mapper" - "github.com/AssetMantle/modules/x/splits/parameters" - "github.com/AssetMantle/modules/x/splits/record" +const ( + ChainID = "testChain" + Denom = "stake" + GenesisAmount = 100000000000 ) -type TestKeepers struct { - MintKeeper helpers.AuxiliaryKeeper +type mockAuxiliaryRequest struct { + mock.Mock } -func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.ParameterManager) { - var legacyAmino = baseHelpers.CodecPrototype().GetLegacyAmino() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - Mapper := mapper.Prototype().Initialize(storeKey) - encodingConfig := simapp.MakeTestEncodingConfig() - appCodec := encodingConfig.Marshaler - ParamsKeeper := paramsKeeper.NewKeeper( - appCodec, - legacyAmino, - paramsStoreKey, - paramsTransientStoreKeys, - ) - parameterManager := parameters.Prototype().Initialize(ParamsKeeper.Subspace("test")) - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - Context := sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - keepers := TestKeepers{ - MintKeeper: keeperPrototype().Initialize(Mapper, parameterManager, []interface{}{}).(helpers.AuxiliaryKeeper), +func (*mockAuxiliaryRequest) Validate() error { + return nil +} + +var _ helpers.AuxiliaryRequest = (*mockAuxiliaryRequest)(nil) +var ( + testSendAmount = sdkTypes.NewInt(100) + + testFromIdentity = baseDocuments.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()) + testFromIdentityID = testFromIdentity.(documents.NameIdentity).GetNameIdentityID() + + testCoinAsset = baseDocuments.NewCoinAsset(Denom) + testCoinAssetID = testCoinAsset.GetCoinAssetID() + + uninitializedCoinAsset = baseDocuments.NewCoinAsset("uninitialized") + uninitializedCoinAssetID = uninitializedCoinAsset.GetCoinAssetID() + + moduleStoreKey = sdkTypes.NewKVStoreKey(constants.ModuleName) + AuxiliaryKeeper = auxiliaryKeeper{mapper.Prototype().Initialize(moduleStoreKey)} + + setContext = func() sdkTypes.Context { + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(moduleStoreKey, sdkTypes.StoreTypeIAVL, memDB) + _ = commitMultiStore.LoadLatestVersion() + return sdkTypes.NewContext(commitMultiStore, protoTendermintTypes.Header{ChainID: ChainID}, false, log.NewNopLogger()) + } - return Context, keepers, Mapper, parameterManager -} + Context = setContext() + + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID), baseTypes.NewSplit(sdkTypes.NewInt(GenesisAmount)))) +) func Test_auxiliaryKeeper_Help(t *testing.T) { - Context, keepers, Mapper, _ := createTestInput(t) - immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) - mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) - classificationID := baseIDs.NewClassificationID(immutables, mutables) - testOwnerIdentityID := baseIDs.NewIdentityID(classificationID, immutables) - testAssetID := baseDocuments.NewCoinAsset("OwnerID").GetCoinAssetID() - testRate := sdkTypes.OneInt() - split := baseTypes.NewSplit(testRate) - keepers.MintKeeper.(auxiliaryKeeper).mapper.NewCollection(Context.Context()).Add(record.NewRecord(baseIDs.NewSplitID(testAssetID, testOwnerIdentityID), split)) - type fields struct { - mapper helpers.Mapper - } - type args struct { - context context.Context - request helpers.AuxiliaryRequest - } tests := []struct { name string - fields fields - args args + setup func() + request helpers.AuxiliaryRequest want helpers.AuxiliaryResponse - wantErr bool + wantErr errors.Error }{ - {"+ve", fields{Mapper}, args{Context.Context(), NewAuxiliaryRequest(testOwnerIdentityID, testAssetID, testRate)}, newAuxiliaryResponse(), false}, + { + "valid request", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + newAuxiliaryResponse(), + nil, + }, + { + "invalid ownerID", + func() {}, + auxiliaryRequest{ + OwnerID: &baseIDs.IdentityID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + nil, + errorConstants.InvalidRequest, + }, + { + "invalid assetID", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: &baseIDs.AssetID{HashID: &baseIDs.HashID{IDBytes: []byte("invalid")}}, + Value: testSendAmount, + }, + nil, + errorConstants.InvalidRequest, + }, { + "invalid value", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: sdkTypes.NewInt(-1), + }, + nil, + errorConstants.InvalidRequest, + }, + { + "invalid request type", + func() {}, + &mockAuxiliaryRequest{}, + nil, + errorConstants.InvalidRequest, + }, + { + "split not found", + func() {}, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: uninitializedCoinAssetID, + Value: testSendAmount, + }, + nil, + errorConstants.EntityNotFound, + }, + { + "with many splits", + func() { + for i := 0; i < 100000; i++ { + _ = AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)). + Add(record.NewRecord(baseIDs.NewSplitID(baseDocuments.NewCoinAsset(random.GenerateUniqueIdentifier()).GetCoinAssetID(), baseDocuments.NewNameIdentity(baseIDs.NewStringID(random.GenerateUniqueIdentifier()), baseData.NewListData()).GetNameIdentityID()), baseTypes.NewSplit(sdkTypes.NewInt(int64(rand.Intn(100000000000)))))) + } + }, + auxiliaryRequest{ + OwnerID: testFromIdentityID, + AssetID: testCoinAssetID, + Value: testSendAmount, + }, + newAuxiliaryResponse(), + nil, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - auxiliaryKeeper := auxiliaryKeeper{ - mapper: tt.fields.mapper, - } - got, err := auxiliaryKeeper.Help(tt.args.context, tt.args.request) - if (err != nil) != tt.wantErr { - t.Errorf("Help() error = %v, wantErr %v", err, tt.wantErr) - return + tt.setup() + + var splitBefore types.Split + if tt.wantErr == nil { + splitBefore = mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID))).GetMappable()) } + got, err := AuxiliaryKeeper.Help(sdkTypes.WrapSDKContext(Context), tt.request) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Help() got = %v, want %v", got, tt.want) } - }) - } -} -func Test_auxiliaryKeeper_Initialize(t *testing.T) { - _, _, Mapper, parameterManager := createTestInput(t) - type fields struct { - mapper helpers.Mapper - } - type args struct { - mapper helpers.Mapper - in1 helpers.ParameterManager - in2 []interface{} - } - tests := []struct { - name string - fields fields - args args - want helpers.Keeper - }{ - {"+ve", fields{Mapper}, args{Mapper, parameterManager, []interface{}{}}, auxiliaryKeeper{Mapper}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - au := auxiliaryKeeper{ - mapper: tt.fields.mapper, - } - if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { - t.Errorf("Initialize() = %v, want %v", got, tt.want) + + if err != nil && tt.wantErr == nil || err == nil && tt.wantErr != nil || err != nil && tt.wantErr != nil && !tt.wantErr.Is(err) { + t.Errorf("\n want error: \n %v \n got error: \n %v", err, tt.wantErr) } - }) - } -} -func Test_keeperPrototype(t *testing.T) { - tests := []struct { - name string - want helpers.AuxiliaryKeeper - }{ - // TODO: Add test cases. - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + if tt.wantErr == nil { + splitAfter := mappable.GetSplit(AuxiliaryKeeper.mapper.NewCollection(sdkTypes.WrapSDKContext(Context)).FetchRecord(key.NewKey(baseIDs.NewSplitID(testCoinAssetID, testFromIdentityID))).GetMappable()) + + if !splitBefore.GetValue().Sub(splitAfter.GetValue()).Equal(testSendAmount) { + t.Errorf("incorrect split value after minting") + } } }) } From 5fdd1ddcf65112c0d4ce7c7fe5ed111da2a3df65 Mon Sep 17 00:00:00 2001 From: deepanshutr Date: Fri, 12 Apr 2024 19:36:23 +0530 Subject: [PATCH 57/57] Enhance validation for auxiliary request The updated code includes enhanced validation processes in the auxiliary request function, now using custom error checking. It ensures the validity of the owner and asset IDs and checks that the value is greater than zero. It also offers improved error messages by replacing govalidator, removing unnecessary 'valid' struct tags and therefore making the overall testing more concise and clear. --- x/splits/auxiliaries/burn/auxiliary_keeper.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/x/splits/auxiliaries/burn/auxiliary_keeper.go b/x/splits/auxiliaries/burn/auxiliary_keeper.go index ba3a4f78b..eaf0af018 100644 --- a/x/splits/auxiliaries/burn/auxiliary_keeper.go +++ b/x/splits/auxiliaries/burn/auxiliary_keeper.go @@ -5,6 +5,8 @@ package burn import ( "context" + errorConstants "github.com/AssetMantle/schema/go/errors/constants" + "reflect" "github.com/AssetMantle/modules/helpers" "github.com/AssetMantle/modules/x/splits/utilities" @@ -17,10 +19,17 @@ type auxiliaryKeeper struct { var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) func (auxiliaryKeeper auxiliaryKeeper) Help(context context.Context, request helpers.AuxiliaryRequest) (helpers.AuxiliaryResponse, error) { - auxiliaryRequest := auxiliaryRequestFromInterface(request) + if err := request.Validate(); err != nil { + return nil, err + } + auxiliaryRequest, ok := request.(auxiliaryRequest) + if !ok { + return nil, errorConstants.InvalidRequest.Wrapf("invalid request type: %s", reflect.TypeOf(request).String()) + } + if _, err := utilities.SubtractSplits(auxiliaryKeeper.mapper.NewCollection(context), auxiliaryRequest.OwnerID, auxiliaryRequest.AssetID, auxiliaryRequest.Value); err != nil { - return newAuxiliaryResponse(), err + return nil, err } return newAuxiliaryResponse(), nil