diff --git a/CHANGELOG.md b/CHANGELOG.md index 63c1d9c07a..fa121665f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ # Version 0.6.1 ## Changes - Updated Cosmos to v0.38.4 (#177) +- Updated the way with which the profiles are created and edited (#170) ## Bug fixes - Fixed the on-chain events usage (#175) diff --git a/app/params/weights.go b/app/params/weights.go index f114121b12..33857c6ad5 100644 --- a/app/params/weights.go +++ b/app/params/weights.go @@ -8,7 +8,6 @@ const ( DefaultWeightMsgRemoveReaction int = 100 DefaultWeightMsgAnswerPoll int = 100 DefaultWeightMsgRegisterReaction int = 100 - DefaultWeightMsgCreateAccount int = 100 - DefaultWeightMsgEditAccount int = 100 + DefaultWeightMsgSaveAccount int = 100 DefaultWeightMsgDeleteAccount int = 100 ) diff --git a/cli_test/cli_profile_test.go b/cli_test/cli_profile_test.go index 3c0c4ede7f..19979bf331 100644 --- a/cli_test/cli_profile_test.go +++ b/cli_test/cli_profile_test.go @@ -28,7 +28,8 @@ func TestDesmosCLIProfileCreate_noFlags(t *testing.T) { require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Create a profile - success, _, sterr := f.TxProfileCreate(moniker, fooAddr, "-y") + success, _, sterr := f.TxProfileSave(fooAddr, "-y", + "--moniker mrBrown") require.True(t, success) require.Empty(t, sterr) tests.WaitForNextNBlocksTM(1, f.Port) @@ -40,11 +41,13 @@ func TestDesmosCLIProfileCreate_noFlags(t *testing.T) { require.Equal(t, profile.Moniker, moniker) // Test --dry-run - success, _, _ = f.TxProfileCreate(moniker, fooAddr, "--dry-run") + success, _, _ = f.TxProfileSave(fooAddr, "--dry-run", + "--moniker mrBrown") require.True(t, success) // Test --generate-only - success, stdout, stderr := f.TxProfileCreate(moniker, fooAddr, "--generate-only=true") + success, stdout, stderr := f.TxProfileSave(fooAddr, "--generate-only=true", + "--moniker mrBrown") require.Empty(t, stderr) require.True(t, success) msg := unmarshalStdTx(f.T, stdout) @@ -77,7 +80,8 @@ func TestDesmosCLIProfileCreate_withFlags(t *testing.T) { require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Create a profile - success, _, sterr := f.TxProfileCreate(moniker, fooAddr, "-y", + success, _, sterr := f.TxProfileSave(fooAddr, "-y", + "--moniker mrBrown", "--name Leonardo", "--surname DiCaprio", "--bio biography", @@ -94,7 +98,8 @@ func TestDesmosCLIProfileCreate_withFlags(t *testing.T) { require.Equal(t, profile.Moniker, moniker) // Test --dry-run - success, _, _ = f.TxProfileCreate(moniker, fooAddr, "--dry-run", + success, _, _ = f.TxProfileSave(fooAddr, "--dry-run", + "--moniker mrBrown", "--name Leonardo", "--surname DiCaprio", "--bio biography", @@ -103,7 +108,8 @@ func TestDesmosCLIProfileCreate_withFlags(t *testing.T) { require.True(t, success) // Test --generate-only - success, stdout, stderr := f.TxProfileCreate(moniker, fooAddr, "--generate-only=true", + success, stdout, stderr := f.TxProfileSave(fooAddr, "--generate-only=true", + "--moniker mrBrown", "--name Leonardo", "--surname DiCaprio", "--bio biography", @@ -142,7 +148,8 @@ func TestDesmosCLIProfileEdit_noFlags(t *testing.T) { require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Create an profile - success, _, sterr := f.TxProfileCreate(moniker, fooAddr, "-y", + success, _, sterr := f.TxProfileSave(fooAddr, "-y", + "--moniker mrBrown", "--name Leonardo", "--surname DiCaprio", "--bio biography", @@ -159,7 +166,7 @@ func TestDesmosCLIProfileEdit_noFlags(t *testing.T) { require.Equal(t, profile.Moniker, moniker) // Edit the profile - success, _, sterr = f.TxProfileEdit(fooAddr, "-y", + success, _, sterr = f.TxProfileSave(fooAddr, "-y", "--moniker mrPink") require.True(t, success) require.Empty(t, sterr) @@ -172,16 +179,17 @@ func TestDesmosCLIProfileEdit_noFlags(t *testing.T) { require.Equal(t, editedProfile.Moniker, newMoniker) //Make sure the profile has been edited - require.Equal(t, storedProfiles[0].Name, editedProfiles[0].Name) - require.Equal(t, storedProfiles[0].Surname, editedProfiles[0].Surname) + var emptyField *string + require.Equal(t, emptyField, editedProfiles[0].Name) + require.Equal(t, emptyField, editedProfiles[0].Surname) // Test --dry-run - success, _, _ = f.TxProfileEdit(fooAddr, "--dry-run", + success, _, _ = f.TxProfileSave(fooAddr, "--dry-run", "--moniker mrPink") require.True(t, success) // Test --generate-only - success, stdout, stderr := f.TxProfileEdit(fooAddr, "--generate-only=true", + success, stdout, stderr := f.TxProfileSave(fooAddr, "--generate-only=true", "--moniker mrPink") require.Empty(t, stderr) require.True(t, success) @@ -216,7 +224,8 @@ func TestDesmosCLIProfileEdit_withFlags(t *testing.T) { require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Create an profile - success, _, sterr := f.TxProfileCreate(moniker, fooAddr, "-y", + success, _, sterr := f.TxProfileSave(fooAddr, "-y", + "--moniker mrBrown", "--name Leonardo", "--surname DiCaprio", "--bio biography", @@ -233,7 +242,7 @@ func TestDesmosCLIProfileEdit_withFlags(t *testing.T) { require.Equal(t, profile.Moniker, moniker) // Edit the profile - success, _, sterr = f.TxProfileEdit(fooAddr, "-y", + success, _, sterr = f.TxProfileSave(fooAddr, "-y", "--moniker mrPink", "--name Leo", "--surname DiCap", @@ -255,7 +264,7 @@ func TestDesmosCLIProfileEdit_withFlags(t *testing.T) { require.NotEqual(t, storedProfiles[0].Surname, editedProfiles[0].Surname) // Test --dry-run - success, _, _ = f.TxProfileEdit(fooAddr, "--dry-run", + success, _, _ = f.TxProfileSave(fooAddr, "--dry-run", "--moniker mrPink", "--name Leo", "--surname DiCap", @@ -265,7 +274,7 @@ func TestDesmosCLIProfileEdit_withFlags(t *testing.T) { require.True(t, success) // Test --generate-only - success, stdout, stderr := f.TxProfileEdit(fooAddr, "--generate-only=true", + success, stdout, stderr := f.TxProfileSave(fooAddr, "--generate-only=true", "--moniker mrPink", "--name Leo", "--surname DiCap", @@ -304,7 +313,8 @@ func TestDesmosCLIProfileDelete(t *testing.T) { require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) // Create an profile - success, _, sterr := f.TxProfileCreate(moniker, fooAddr, "-y") + success, _, sterr := f.TxProfileSave(fooAddr, "-y", + "--moniker mrBrown") require.True(t, success) require.Empty(t, sterr) tests.WaitForNextNBlocksTM(1, f.Port) diff --git a/cli_test/test_helpers.go b/cli_test/test_helpers.go index 38306bfac3..57f3442bef 100644 --- a/cli_test/test_helpers.go +++ b/cli_test/test_helpers.go @@ -457,14 +457,8 @@ func (f *Fixtures) TxPostsRegisterReaction(shortCode, value, subspace string, fr //___________________________________________________________________________________ // desmoscli tx profile -func (f *Fixtures) TxProfileCreate(moniker string, from sdk.AccAddress, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf(`%s tx profiles create %s --keyring-backend=test --from=%s %v`, - f.DesmosliBinary, moniker, from, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -func (f *Fixtures) TxProfileEdit(from sdk.AccAddress, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf(`%s tx profiles edit --keyring-backend=test --from=%s %v`, +func (f *Fixtures) TxProfileSave(from sdk.AccAddress, flags ...string) (bool, string, string) { + cmd := fmt.Sprintf(`%s tx profiles save --keyring-backend=test --from=%s %v`, f.DesmosliBinary, from, f.Flags()) return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) } diff --git a/docs/developers/msgs/create-profile.md b/docs/developers/msgs/create-profile.md deleted file mode 100644 index 31730d2123..0000000000 --- a/docs/developers/msgs/create-profile.md +++ /dev/null @@ -1,56 +0,0 @@ -# `MsgCreateProfile` -This message allows you to create a new profile. -If you want to know more about the `Profile` type, you can do so inside the [`Profile` type documentation page](../../types/profile.md) - -## Structure -````json -{ - "type": "desmos/MsgCreateProfile", - "value": { - "moniker": "", - "name": "", - "surname": "", - "bio": "", - "pictures": { - "profile": "", - "cover": "" - }, - "creator": "" - } -} -```` - -### Attributes -| Attribute | Type | Description | -| :-------: | :----: | :-------- | -| `moniker` | String | Moniker of the user's profile | -| `name` | String | (Optional) Name of the user | -| `surname` | String | (Optional) Surname of the user | -| `bio` | String | (Optional) Biography of the user | -| `pictures` | Object | (Optional) Object containing all the information related to the profile's pictures | -| `creator` | String | Desmos address of the user that is creating the profile | - -## Example -````json -{ - "type": "desmos/MsgCreateProfile", - "value": { - "moniker": "Eva01", - "name": "Shinji", - "surname": "Ikari", - "bio": "evaPilot", - "pictures": { - "profile": "https://shorturl.at/adnX3", - "cover": "https://shorturl.at/cgpyF" - }, - "creator": "desmos12a2y7fflz6g4e5gn0mh0n9dkrzllj0q5vx7c6t" - } -} -```` - -## Message action -The action associated to this message is the following: - -``` -create_profile -``` \ No newline at end of file diff --git a/docs/developers/msgs/edit-profile.md b/docs/developers/msgs/save-profile.md similarity index 73% rename from docs/developers/msgs/edit-profile.md rename to docs/developers/msgs/save-profile.md index 368deba17a..5565544b26 100644 --- a/docs/developers/msgs/edit-profile.md +++ b/docs/developers/msgs/save-profile.md @@ -1,12 +1,12 @@ -# `MsgEditProfile` -This message allows you to edit a previously created profile. +# `MsgSaveProfile` +This message allows you to save a new profile or edit an existent one. ## Structure ````json { - "type": "desmos/MsgEditProfile", + "type": "desmos/MsgSaveProfile", "value": { - "new_moniker": "", + "moniker": "", "name": "", "surname": "", "bio": "", @@ -22,22 +22,21 @@ This message allows you to edit a previously created profile. ### Attributes | Attribute | Type | Description | | :-------: | :----: | :-------- | -| `new_moniker` | String | (Optional) New moniker of the user's profile | +| `moniker` | String | Moniker of the user's profile | | `name` | String | (Optional) Name of the user | | `surname` | String | (Optional) Surname of the user | | `bio` | String | (Optional) Biography of the user | | `pictures` | Object | (Optional) Object containing all the information related to the profile's pictures | | `creator` | String | Desmos address of the user that is editing the profile | -All the attributes will not accept the string `default` as a value because it's reserved for internal operations. - +If you are editing an existing profile you should fill all the existent fields otherwise they will be set as nil. ## Example ````json { - "type": "desmos/MsgEditProfile", + "type": "desmos/MsgSaveProfile", "value": { - "new_moniker": "Eva00", + "moniker": "Eva00", "name": "Rei", "surname": "Ayanami", "bio": "evaPilot", @@ -54,6 +53,6 @@ All the attributes will not accept the string `default` as a value because it's The action associated to this message is the following: ``` -edit_profile +save_profile ``` diff --git a/docs/developers/perform-transactions.md b/docs/developers/perform-transactions.md index cade6cebea..9bf9143fdf 100644 --- a/docs/developers/perform-transactions.md +++ b/docs/developers/perform-transactions.md @@ -17,6 +17,5 @@ Here is the list of currently available [messages](developer-faq.md#what-is-a-me * [`MsgRegisterReaction`](msgs/register-reaction.md): allows you to register a reaction. ### Profile -* [`MsgCreateProfile`](msgs/create-profile.md): allows you to create a new profile for a user. -* [`MsgEditProfile`](msgs/edit-profile.md): allows you to edit an existing profile. +* [`MsgSaveProfile`](docs/developers/msgs/save-profile.md): allows you to create or edit an existing profile. * [`MsgDeleteProfile`](msgs/delete-profile.md): allows you to delete an existing profile. \ No newline at end of file diff --git a/x/magpie/alias.go b/x/magpie/alias.go index bb725e5865..382941c615 100644 --- a/x/magpie/alias.go +++ b/x/magpie/alias.go @@ -13,53 +13,51 @@ import ( const ( QuerySessions = keeper.QuerySessions OpWeightMsgCreatePost = simulation.OpWeightMsgCreatePost + ModuleName = types.ModuleName + RouterKey = types.RouterKey + StoreKey = types.StoreKey + ActionCreationSession = types.ActionCreationSession EventTypeCreateSession = types.EventTypeCreateSession AttributeKeySessionID = types.AttributeKeySessionID AttributeKeyNamespace = types.AttributeKeyNamespace AttributeKeyExternalOwner = types.AttributeKeyExternalOwner AttributeKeyExpiry = types.AttributeKeyExpiry AttributeValueCategory = types.AttributeValueCategory - ModuleName = types.ModuleName - RouterKey = types.RouterKey - StoreKey = types.StoreKey - ActionCreationSession = types.ActionCreationSession ) var ( // functions aliases - - NewHandler = keeper.NewHandler NewKeeper = keeper.NewKeeper NewQuerier = keeper.NewQuerier - DecodeStore = simulation.DecodeStore - RandomizedGenState = simulation.RandomizedGenState + NewHandler = keeper.NewHandler + RandomSessionData = simulation.RandomSessionData WeightedOperations = simulation.WeightedOperations SimulateMsgCreateSession = simulation.SimulateMsgCreateSession - RandomSessionData = simulation.RandomSessionData - RegisterCodec = types.RegisterCodec + RandomizedGenState = simulation.RandomizedGenState + DecodeStore = simulation.DecodeStore + SessionStoreKey = types.SessionStoreKey + ParseSessionID = types.ParseSessionID + NewSession = types.NewSession NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState ValidateGenesis = types.ValidateGenesis - SessionStoreKey = types.SessionStoreKey + RegisterCodec = types.RegisterCodec NewMsgCreateSession = types.NewMsgCreateSession - ParseSessionID = types.ParseSessionID - NewSession = types.NewSession // variable aliases - RandomNamespaces = simulation.RandomNamespaces - ModuleCdc = types.ModuleCdc SessionLengthKey = types.SessionLengthKey LastSessionIDStoreKey = types.LastSessionIDStoreKey SessionStorePrefix = types.SessionStorePrefix + ModuleCdc = types.ModuleCdc ) type ( - Keeper = keeper.Keeper - SessionData = simulation.SessionData - GenesisState = types.GenesisState - MsgCreateSession = types.MsgCreateSession SessionID = types.SessionID Session = types.Session Sessions = types.Sessions + GenesisState = types.GenesisState + MsgCreateSession = types.MsgCreateSession + Keeper = keeper.Keeper + SessionData = simulation.SessionData ) diff --git a/x/posts/alias.go b/x/posts/alias.go index b96dbd2933..cdf980aeee 100644 --- a/x/posts/alias.go +++ b/x/posts/alias.go @@ -66,16 +66,46 @@ const ( var ( // functions aliases + SimulateMsgAddPostReaction = simulation.SimulateMsgAddPostReaction + SimulateMsgRemovePostReaction = simulation.SimulateMsgRemovePostReaction + SimulateMsgRegisterReaction = simulation.SimulateMsgRegisterReaction + SimulateMsgCreatePost = simulation.SimulateMsgCreatePost + SimulateMsgEditPost = simulation.SimulateMsgEditPost + RandomPost = simulation.RandomPost + RandomPostData = simulation.RandomPostData + RandomPostReactionData = simulation.RandomPostReactionData + RandomPostReactionValue = simulation.RandomPostReactionValue + RandomPostID = simulation.RandomPostID + RandomMessage = simulation.RandomMessage + RandomSubspace = simulation.RandomSubspace + RandomHashtag = simulation.RandomHashtag + RandomMedias = simulation.RandomMedias + RandomPollData = simulation.RandomPollData + GetAccount = simulation.GetAccount + RandomReactionValue = simulation.RandomReactionValue + RandomReactionShortCode = simulation.RandomReactionShortCode + RandomReactionData = simulation.RandomReactionData + RegisteredReactionsData = simulation.RegisteredReactionsData + RandomEmojiPostReaction = simulation.RandomEmojiPostReaction + WeightedOperations = simulation.WeightedOperations + RandomizedGenState = simulation.RandomizedGenState + DecodeStore = simulation.DecodeStore + SimulateMsgAnswerToPoll = simulation.SimulateMsgAnswerToPoll + DefaultQueryPostsParams = types.DefaultQueryPostsParams + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + RegisterCodec = types.RegisterCodec + ComputeID = models.ComputeID + ParsePostID = models.ParsePostID + NewPost = models.NewPost NewPostResponse = models.NewPostResponse - RegisterModelsCodec = models.RegisterModelsCodec PostStoreKey = models.PostStoreKey PostCommentsStoreKey = models.PostCommentsStoreKey PostReactionsStoreKey = models.PostReactionsStoreKey ReactionsStoreKey = models.ReactionsStoreKey PollAnswersStoreKey = models.PollAnswersStoreKey - ComputeID = models.ComputeID - ParsePostID = models.ParsePostID - NewPost = models.NewPost + RegisterModelsCodec = models.RegisterModelsCodec NewPostMedia = common.NewPostMedia ValidateURI = common.ValidateURI NewPostMedias = common.NewPostMedias @@ -91,56 +121,24 @@ var ( NewReaction = reactions.NewReaction IsEmoji = reactions.IsEmoji NewReactions = reactions.NewReactions - RegisterMessagesCodec = msgs.RegisterMessagesCodec - NewMsgCreatePost = msgs.NewMsgCreatePost - NewMsgEditPost = msgs.NewMsgEditPost - NewMsgAnswerPoll = msgs.NewMsgAnswerPoll NewMsgAddPostReaction = msgs.NewMsgAddPostReaction NewMsgRemovePostReaction = msgs.NewMsgRemovePostReaction + NewMsgAnswerPoll = msgs.NewMsgAnswerPoll + NewMsgCreatePost = msgs.NewMsgCreatePost + NewMsgEditPost = msgs.NewMsgEditPost NewMsgRegisterReaction = msgs.NewMsgRegisterReaction + RegisterMessagesCodec = msgs.RegisterMessagesCodec NewHandler = keeper.NewHandler + NewKeeper = keeper.NewKeeper + NewQuerier = keeper.NewQuerier RegisterInvariants = keeper.RegisterInvariants AllInvariants = keeper.AllInvariants ValidPostsInvariant = keeper.ValidPostsInvariant ValidCommentsDateInvariant = keeper.ValidCommentsDateInvariant ValidPostForReactionsInvariant = keeper.ValidPostForReactionsInvariant ValidPollForPollAnswersInvariant = keeper.ValidPollForPollAnswersInvariant - NewKeeper = keeper.NewKeeper - NewQuerier = keeper.NewQuerier - DecodeStore = simulation.DecodeStore - RandomizedGenState = simulation.RandomizedGenState - WeightedOperations = simulation.WeightedOperations - SimulateMsgAnswerToPoll = simulation.SimulateMsgAnswerToPoll - SimulateMsgCreatePost = simulation.SimulateMsgCreatePost - SimulateMsgEditPost = simulation.SimulateMsgEditPost - SimulateMsgAddPostReaction = simulation.SimulateMsgAddPostReaction - SimulateMsgRemovePostReaction = simulation.SimulateMsgRemovePostReaction - SimulateMsgRegisterReaction = simulation.SimulateMsgRegisterReaction - RandomPost = simulation.RandomPost - RandomPostData = simulation.RandomPostData - RandomPostReactionData = simulation.RandomPostReactionData - RandomPostReactionValue = simulation.RandomPostReactionValue - RandomPostID = simulation.RandomPostID - RandomMessage = simulation.RandomMessage - RandomSubspace = simulation.RandomSubspace - RandomHashtag = simulation.RandomHashtag - RandomMedias = simulation.RandomMedias - RandomPollData = simulation.RandomPollData - GetAccount = simulation.GetAccount - RandomReactionValue = simulation.RandomReactionValue - RandomReactionShortCode = simulation.RandomReactionShortCode - RandomReactionData = simulation.RandomReactionData - RegisteredReactionsData = simulation.RegisteredReactionsData - RegisterCodec = types.RegisterCodec - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - ValidateGenesis = types.ValidateGenesis - DefaultQueryPostsParams = types.DefaultQueryPostsParams // variable aliases - RandomMimeTypes = simulation.RandomMimeTypes - RandomHosts = simulation.RandomHosts - ModuleCdc = types.ModuleCdc ModelsCdc = models.ModelsCdc Sha256RegEx = common.Sha256RegEx HashtagRegEx = common.HashtagRegEx @@ -153,20 +151,34 @@ var ( ReactionsStorePrefix = common.ReactionsStorePrefix PollAnswersStorePrefix = common.PollAnswersStorePrefix MsgsCodec = msgs.MsgsCodec + RandomMimeTypes = simulation.RandomMimeTypes + RandomHosts = simulation.RandomHosts + ModuleCdc = types.ModuleCdc ) type ( + PostReaction = reactions.PostReaction + PostReactions = reactions.PostReactions + Reaction = reactions.Reaction + Reactions = reactions.Reactions + MsgAddPostReaction = msgs.MsgAddPostReaction + MsgRemovePostReaction = msgs.MsgRemovePostReaction + MsgAnswerPoll = msgs.MsgAnswerPoll + MsgCreatePost = msgs.MsgCreatePost + MsgEditPost = msgs.MsgEditPost + MsgRegisterReaction = msgs.MsgRegisterReaction + Keeper = keeper.Keeper PostData = simulation.PostData PostReactionData = simulation.PostReactionData ReactionData = simulation.ReactionData - GenesisState = types.GenesisState QueryPostsParams = types.QueryPostsParams - PostQueryResponse = models.PostQueryResponse - PollAnswersQueryResponse = models.PollAnswersQueryResponse + GenesisState = types.GenesisState PostID = models.PostID PostIDs = models.PostIDs Post = models.Post Posts = models.Posts + PostQueryResponse = models.PostQueryResponse + PollAnswersQueryResponse = models.PollAnswersQueryResponse PostMedia = common.PostMedia PostMedias = common.PostMedias OptionalData = common.OptionalData @@ -177,15 +189,4 @@ type ( PollData = polls.PollData UserAnswer = polls.UserAnswer UserAnswers = polls.UserAnswers - PostReaction = reactions.PostReaction - PostReactions = reactions.PostReactions - Reaction = reactions.Reaction - Reactions = reactions.Reactions - MsgCreatePost = msgs.MsgCreatePost - MsgEditPost = msgs.MsgEditPost - MsgAnswerPoll = msgs.MsgAnswerPoll - MsgAddPostReaction = msgs.MsgAddPostReaction - MsgRemovePostReaction = msgs.MsgRemovePostReaction - MsgRegisterReaction = msgs.MsgRegisterReaction - Keeper = keeper.Keeper ) diff --git a/x/posts/internal/types/alias.go b/x/posts/internal/types/alias.go index 0bbb39faa5..28013b86c1 100644 --- a/x/posts/internal/types/alias.go +++ b/x/posts/internal/types/alias.go @@ -38,16 +38,28 @@ const ( var ( // functions aliases + NewPostReaction = reactions.NewPostReaction + NewPostReactions = reactions.NewPostReactions + NewReaction = reactions.NewReaction + IsEmoji = reactions.IsEmoji + NewReactions = reactions.NewReactions + NewMsgCreatePost = msgs.NewMsgCreatePost + NewMsgEditPost = msgs.NewMsgEditPost + NewMsgRegisterReaction = msgs.NewMsgRegisterReaction + RegisterMessagesCodec = msgs.RegisterMessagesCodec + NewMsgAddPostReaction = msgs.NewMsgAddPostReaction + NewMsgRemovePostReaction = msgs.NewMsgRemovePostReaction + NewMsgAnswerPoll = msgs.NewMsgAnswerPoll ComputeID = models.ComputeID ParsePostID = models.ParsePostID NewPost = models.NewPost NewPostResponse = models.NewPostResponse - RegisterModelsCodec = models.RegisterModelsCodec PostStoreKey = models.PostStoreKey PostCommentsStoreKey = models.PostCommentsStoreKey PostReactionsStoreKey = models.PostReactionsStoreKey ReactionsStoreKey = models.ReactionsStoreKey PollAnswersStoreKey = models.PollAnswersStoreKey + RegisterModelsCodec = models.RegisterModelsCodec NewPostMedia = common.NewPostMedia ValidateURI = common.ValidateURI NewPostMedias = common.NewPostMedias @@ -58,20 +70,9 @@ var ( ArePollDataEquals = polls.ArePollDataEquals NewUserAnswer = polls.NewUserAnswer NewUserAnswers = polls.NewUserAnswers - NewPostReaction = reactions.NewPostReaction - NewPostReactions = reactions.NewPostReactions - NewReaction = reactions.NewReaction - IsEmoji = reactions.IsEmoji - NewReactions = reactions.NewReactions - RegisterMessagesCodec = msgs.RegisterMessagesCodec - NewMsgCreatePost = msgs.NewMsgCreatePost - NewMsgEditPost = msgs.NewMsgEditPost - NewMsgAnswerPoll = msgs.NewMsgAnswerPoll - NewMsgAddPostReaction = msgs.NewMsgAddPostReaction - NewMsgRemovePostReaction = msgs.NewMsgRemovePostReaction - NewMsgRegisterReaction = msgs.NewMsgRegisterReaction // variable aliases + ModelsCdc = models.ModelsCdc Sha256RegEx = common.Sha256RegEx HashtagRegEx = common.HashtagRegEx ShortCodeRegEx = common.ShortCodeRegEx @@ -83,10 +84,19 @@ var ( ReactionsStorePrefix = common.ReactionsStorePrefix PollAnswersStorePrefix = common.PollAnswersStorePrefix MsgsCodec = msgs.MsgsCodec - ModelsCdc = models.ModelsCdc ) type ( + PostID = models.PostID + PostIDs = models.PostIDs + Post = models.Post + Posts = models.Posts + PostQueryResponse = models.PostQueryResponse + PollAnswersQueryResponse = models.PollAnswersQueryResponse + PostMedia = common.PostMedia + PostMedias = common.PostMedias + OptionalData = common.OptionalData + KeyValue = common.KeyValue AnswerID = polls.AnswerID PollAnswer = polls.PollAnswer PollAnswers = polls.PollAnswers @@ -99,18 +109,8 @@ type ( Reactions = reactions.Reactions MsgCreatePost = msgs.MsgCreatePost MsgEditPost = msgs.MsgEditPost - MsgAnswerPoll = msgs.MsgAnswerPoll + MsgRegisterReaction = msgs.MsgRegisterReaction MsgAddPostReaction = msgs.MsgAddPostReaction MsgRemovePostReaction = msgs.MsgRemovePostReaction - MsgRegisterReaction = msgs.MsgRegisterReaction - PostID = models.PostID - PostIDs = models.PostIDs - Post = models.Post - Posts = models.Posts - PostQueryResponse = models.PostQueryResponse - PollAnswersQueryResponse = models.PollAnswersQueryResponse - PostMedia = common.PostMedia - PostMedias = common.PostMedias - OptionalData = common.OptionalData - KeyValue = common.KeyValue + MsgAnswerPoll = msgs.MsgAnswerPoll ) diff --git a/x/posts/internal/types/models/alias.go b/x/posts/internal/types/models/alias.go index a2ca62c022..ebc0aa0ddf 100644 --- a/x/posts/internal/types/models/alias.go +++ b/x/posts/internal/types/models/alias.go @@ -66,10 +66,10 @@ var ( ) type ( - OptionalData = common.OptionalData - KeyValue = common.KeyValue PostMedia = common.PostMedia PostMedias = common.PostMedias + OptionalData = common.OptionalData + KeyValue = common.KeyValue AnswerID = polls.AnswerID PollAnswer = polls.PollAnswer PollAnswers = polls.PollAnswers diff --git a/x/profile/alias.go b/x/profile/alias.go index 589db3cdb9..68c06d4eb5 100644 --- a/x/profile/alias.go +++ b/x/profile/alias.go @@ -11,12 +11,10 @@ import ( ) const ( - OpWeightMsgCreateProfile = simulation.OpWeightMsgCreateProfile - OpWeightMsgEditProfile = simulation.OpWeightMsgEditProfile + OpWeightMsgSaveProfile = simulation.OpWeightMsgSaveProfile OpWeightMsgDeleteProfile = simulation.OpWeightMsgDeleteProfile DefaultGasValue = simulation.DefaultGasValue - EventTypeProfileCreated = types.EventTypeProfileCreated - EventTypeProfileEdited = types.EventTypeProfileEdited + EventTypeProfileSaved = types.EventTypeProfileSaved EventTypeProfileDeleted = types.EventTypeProfileDeleted AttributeProfileMoniker = types.AttributeProfileMoniker AttributeProfileCreator = types.AttributeProfileCreator @@ -25,10 +23,10 @@ const ( StoreKey = types.StoreKey MinNameSurnameLength = types.MinNameSurnameLength MaxNameSurnameLength = types.MaxNameSurnameLength + MinMonikerLength = types.MinMonikerLength MaxMonikerLength = types.MaxMonikerLength MaxBioLength = types.MaxBioLength - ActionCreateProfile = types.ActionCreateProfile - ActionEditProfile = types.ActionEditProfile + ActionSaveProfile = types.ActionSaveProfile ActionDeleteProfile = types.ActionDeleteProfile QuerierRoute = types.QuerierRoute QueryProfile = types.QueryProfile @@ -37,17 +35,22 @@ const ( var ( // functions aliases + NewPictures = types.NewPictures + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + RegisterCodec = types.RegisterCodec + NewMsgSaveProfile = types.NewMsgSaveProfile + NewMsgDeleteProfile = types.NewMsgDeleteProfile + ProfileStoreKey = types.ProfileStoreKey + MonikerStoreKey = types.MonikerStoreKey + NewProfile = types.NewProfile + NewHandler = keeper.NewHandler + NewKeeper = keeper.NewKeeper + NewQuerier = keeper.NewQuerier RegisterInvariants = keeper.RegisterInvariants AllInvariants = keeper.AllInvariants ValidProfileInvariant = keeper.ValidProfileInvariant - NewKeeper = keeper.NewKeeper - NewQuerier = keeper.NewQuerier - NewHandler = keeper.NewHandler - GetEditedProfile = keeper.GetEditedProfile - WeightedOperations = simulation.WeightedOperations - SimulateMsgCreateProfile = simulation.SimulateMsgCreateProfile - SimulateMsgEditProfile = simulation.SimulateMsgEditProfile - SimulateMsgDeleteProfile = simulation.SimulateMsgDeleteProfile RandomProfileData = simulation.RandomProfileData RandomProfile = simulation.RandomProfile RandomMoniker = simulation.RandomMoniker @@ -57,20 +60,11 @@ var ( RandomProfilePic = simulation.RandomProfilePic RandomProfileCover = simulation.RandomProfileCover GetSimAccount = simulation.GetSimAccount - DecodeStore = simulation.DecodeStore + WeightedOperations = simulation.WeightedOperations RandomizedGenState = simulation.RandomizedGenState - RegisterCodec = types.RegisterCodec - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - ValidateGenesis = types.ValidateGenesis - ProfileStoreKey = types.ProfileStoreKey - MonikerStoreKey = types.MonikerStoreKey - NewMsgCreateProfile = types.NewMsgCreateProfile - NewMsgEditProfile = types.NewMsgEditProfile - NewMsgDeleteProfile = types.NewMsgDeleteProfile - NewPictures = types.NewPictures - ValidateURI = types.ValidateURI - NewProfile = types.NewProfile + DecodeStore = simulation.DecodeStore + SimulateMsgSaveProfile = simulation.SimulateMsgSaveProfile + SimulateMsgDeleteProfile = simulation.SimulateMsgDeleteProfile // variable aliases ModuleCdc = types.ModuleCdc @@ -83,11 +77,10 @@ var ( type ( Keeper = keeper.Keeper ProfileData = simulation.ProfileData + Pictures = types.Pictures GenesisState = types.GenesisState - MsgCreateProfile = types.MsgCreateProfile - MsgEditProfile = types.MsgEditProfile + MsgSaveProfile = types.MsgSaveProfile MsgDeleteProfile = types.MsgDeleteProfile - Pictures = types.Pictures Profile = types.Profile Profiles = types.Profiles ) diff --git a/x/profile/client/cli/keys.go b/x/profile/client/cli/keys.go index 249e18d017..daeba89e5d 100644 --- a/x/profile/client/cli/keys.go +++ b/x/profile/client/cli/keys.go @@ -6,5 +6,5 @@ const ( flagBio = "bio" flagProfilePic = "picture" flagProfileCover = "cover" - flagNewMoniker = "moniker" + flagMoniker = "moniker" ) diff --git a/x/profile/client/cli/tx.go b/x/profile/client/cli/tx.go index b41e580560..7bae804283 100644 --- a/x/profile/client/cli/tx.go +++ b/x/profile/client/cli/tx.go @@ -29,92 +29,38 @@ func GetTxCmd(_ string, cdc *codec.Codec) *cobra.Command { } profileTxCmd.AddCommand(flags.PostCommands( - GetCmdCreateProfile(cdc), - GetCmdEditProfile(cdc), + GetCmdSaveProfile(cdc), GetCmdDeleteProfile(cdc), )...) return profileTxCmd } -func GetFlagValueOrNilOnDefault(flag string) *string { +func getFlagValueOrNilOnDefault(flag string) *string { flagValue := viper.GetString(flag) - if flagValue == "default" { + if flagValue == "" { return nil } return &flagValue } -// GetCmdCreateProfile is the CLI command for creating a profile -func GetCmdCreateProfile(cdc *codec.Codec) *cobra.Command { +// GetCmdSaveProfile is the CLI command for saving an profile +func GetCmdSaveProfile(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ - Use: "create [moniker]", - Short: "Create a new profile", + Use: "save", + Short: "Save a profile", Long: fmt.Sprintf(` -Create a new profile specifying the moniker, name, surname, bio, a profile picture and cover. -Every data except the moniker is optional, feel free to specify only what you want other people to know publicly about you. +Save a new profile or edit an existing one specifying the moniker, name, surname, bio, a profile picture and cover. +Every data is optional except for the moniker. +If you are editing an existing profile you should fill all the existent fields otherwise they will be set as nil. -E.g (only with moniker) -%s tx profile create leoDiCap - -E.g (with all the other optional fields) -%s tx profiles create leoDiCap \ +%s tx profiles save \ + --moniker "DiCapLeo" \ --name "Leonardo" \ --surname "Di Caprio" \ --bio "Hollywood actor. Proud environmentalist" \ --picture "https://profilePic.jpg" --cover "https://profileCover.jpg" -`, version.ClientName, version.ClientName), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) - - picture := GetFlagValueOrNilOnDefault(flagProfilePic) - cover := GetFlagValueOrNilOnDefault(flagProfileCover) - var pictures *types.Pictures - if picture != nil && cover != nil { - pictures = types.NewPictures(picture, cover) - } - name := GetFlagValueOrNilOnDefault(flagName) - surname := GetFlagValueOrNilOnDefault(flagSurname) - bio := GetFlagValueOrNilOnDefault(flagBio) - - msg := types.NewMsgCreateProfile(args[0], name, surname, bio, pictures, cliCtx.FromAddress) - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagName, "default", "Name of the profile") - cmd.Flags().String(flagSurname, "default", "Surname of the profile") - cmd.Flags().String(flagBio, "default", "Biography of the profile") - cmd.Flags().String(flagProfilePic, "default", "Profile related picture") - cmd.Flags().String(flagProfileCover, "default", "Profile related cover picture") - - return cmd -} - -// GetCmdEditProfile is the CLI command for editing an profile -func GetCmdEditProfile(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "edit", - Short: "Edit an existent profile", - Long: fmt.Sprintf(` -Edit an existing profile specifying the new moniker, name, surname, bio, a profile picture and cover. -Every data is optional. - -All the attributes will not accept the string "default" as a value because it's reserved for internal operations. - -E.g (with all the other optional fields) -%s tx profiles edit \ - --moniker "DiCapLeo" \ - --name "Leo" \ - --surname "Di Cap" \ - --bio "Hollywood actor. Proud environmentalist" \ - --picture "https://profilePic.jpg" - --cover "https://profileCover.jpg" `, version.ClientName), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { @@ -122,25 +68,25 @@ E.g (with all the other optional fields) txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) - picture := GetFlagValueOrNilOnDefault(flagProfilePic) - cover := GetFlagValueOrNilOnDefault(flagProfileCover) - newMoniker := GetFlagValueOrNilOnDefault(flagNewMoniker) - name := GetFlagValueOrNilOnDefault(flagName) - surname := GetFlagValueOrNilOnDefault(flagSurname) - bio := GetFlagValueOrNilOnDefault(flagBio) + moniker := viper.GetString(flagMoniker) + picture := getFlagValueOrNilOnDefault(flagProfilePic) + cover := getFlagValueOrNilOnDefault(flagProfileCover) + name := getFlagValueOrNilOnDefault(flagName) + surname := getFlagValueOrNilOnDefault(flagSurname) + bio := getFlagValueOrNilOnDefault(flagBio) - msg := types.NewMsgEditProfile(newMoniker, name, surname, bio, picture, cover, cliCtx.FromAddress) + msg := types.NewMsgSaveProfile(moniker, name, surname, bio, picture, cover, cliCtx.FromAddress) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } - cmd.Flags().String(flagNewMoniker, "default", "New moniker of the profile") - cmd.Flags().String(flagName, "default", "Name of the profile") - cmd.Flags().String(flagSurname, "default", "Surname of the profile") - cmd.Flags().String(flagBio, "default", "Biography of the profile") - cmd.Flags().String(flagProfilePic, "default", "Profile related profile picture") - cmd.Flags().String(flagProfileCover, "default", "Profile related profile cover") + cmd.Flags().String(flagMoniker, "", "Moniker of the profile") + cmd.Flags().String(flagName, "", "Name of the profile") + cmd.Flags().String(flagSurname, "", "Surname of the profile") + cmd.Flags().String(flagBio, "", "Biography of the profile") + cmd.Flags().String(flagProfilePic, "", "Profile related profile picture") + cmd.Flags().String(flagProfileCover, "", "Profile related profile cover") return cmd } diff --git a/x/profile/client/rest/rest.go b/x/profile/client/rest/rest.go index 322e7f849a..24d87e1f7c 100644 --- a/x/profile/client/rest/rest.go +++ b/x/profile/client/rest/rest.go @@ -13,20 +13,10 @@ func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { registerQueryRoutes(cliCtx, r) } -// CreateProfileReq defines the properties of a profile creation request's body -type CreateProfileReq struct { - BaseReq rest.BaseReq `json:"base_req"` - Moniker string `json:"moniker"` - Name *string `json:"name,omitempty"` - Surname *string `json:"surname,omitempty"` - Bio *string `json:"bio,omitempty"` - Pictures *types.Pictures `json:"pictures,omitempty"` -} - -// EditProfileReq defines the properties of a profile edit request's body -type EditProfileReq struct { +// SaveProfileReq defines the properties of a profile save request's body +type SaveProfileReq struct { BaseReq rest.BaseReq `json:"base_req"` - NewMoniker *string `json:"new_moniker"` + NewMoniker string `json:"moniker"` Name *string `json:"name,omitempty"` Surname *string `json:"surname,omitempty"` Bio *string `json:"bio,omitempty"` diff --git a/x/profile/client/rest/tx.go b/x/profile/client/rest/tx.go index 4f113b70c8..f8f7cd6719 100644 --- a/x/profile/client/rest/tx.go +++ b/x/profile/client/rest/tx.go @@ -12,47 +12,14 @@ import ( ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { - r.HandleFunc("/profiles", createProfileHandler(cliCtx)).Methods("POST") - r.HandleFunc("/profiles/{address}", editProfileHandler(cliCtx)).Methods("PUT") + r.HandleFunc("/profiles/{address}", saveProfileHandler(cliCtx)).Methods("PUT") r.HandleFunc("/profiles/{address}", deleteProfileHandler(cliCtx)).Methods("DELETE") } -func createProfileHandler(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req CreateProfileReq - - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") - return - } - - baseReq := req.BaseReq.Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - - addr, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgCreateProfile(req.Moniker, req.Name, req.Surname, req.Bio, req.Pictures, addr) - - err = msg.ValidateBasic() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) - } -} - -func editProfileHandler(cliCtx context.CLIContext) http.HandlerFunc { +func saveProfileHandler(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - var req EditProfileReq + var req SaveProfileReq if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") @@ -70,7 +37,7 @@ func editProfileHandler(cliCtx context.CLIContext) http.HandlerFunc { return } - msg := types.NewMsgEditProfile( + msg := types.NewMsgSaveProfile( req.NewMoniker, req.Name, req.Surname, diff --git a/x/profile/internal/keeper/handler.go b/x/profile/internal/keeper/handler.go index 82bae598c9..a7c58c0d47 100644 --- a/x/profile/internal/keeper/handler.go +++ b/x/profile/internal/keeper/handler.go @@ -15,10 +15,8 @@ func NewHandler(keeper Keeper) sdk.Handler { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - case types.MsgCreateProfile: - return handleMsgCreateProfile(ctx, keeper, msg) - case types.MsgEditProfile: - return handleMsgEditProfile(ctx, keeper, msg) + case types.MsgSaveProfile: + return handleMsgSaveProfile(ctx, keeper, msg) case types.MsgDeleteProfile: return handleMsgDeleteProfile(ctx, keeper, msg) default: @@ -28,87 +26,20 @@ func NewHandler(keeper Keeper) sdk.Handler { } } -// handleMsgCreateProfile handles the creation of a profile -func handleMsgCreateProfile(ctx sdk.Context, keeper Keeper, msg types.MsgCreateProfile) (*sdk.Result, error) { - // check if an account with the same moniker already exists - // this check prevent the same user to create the same account multiple times - if address := keeper.GetMonikerRelatedAddress(ctx, msg.Moniker); address.Equals(msg.Creator) { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("An account with %s moniker already exists", msg.Moniker)) +// handleMsgSaveProfile handles the creation/edit of a profile +func handleMsgSaveProfile(ctx sdk.Context, keeper Keeper, msg types.MsgSaveProfile) (*sdk.Result, error) { + profile, found := keeper.GetProfile(ctx, msg.Creator) + if !found { + profile = types.NewProfile(msg.Creator) } - - account := types.NewProfile(msg.Moniker, msg.Creator). + // replace all editable fields (clients should autofill existing values) + profile = profile. + WithMoniker(msg.Moniker). WithName(msg.Name). WithSurname(msg.Surname). WithBio(msg.Bio). - WithPictures(msg.Pictures) - - // Before saving this method checks if an account with the same moniker exist - err := keeper.SaveProfile(ctx, account) - if err != nil { - return nil, err - } - - createEvent := sdk.NewEvent( - types.EventTypeProfileCreated, - sdk.NewAttribute(types.AttributeProfileMoniker, account.Moniker), - sdk.NewAttribute(types.AttributeProfileCreator, account.Creator.String()), - ) + WithPictures(msg.ProfilePic, msg.ProfileCov) - ctx.EventManager().EmitEvent(createEvent) - - result := sdk.Result{ - Data: keeper.Cdc.MustMarshalBinaryLengthPrefixed(account.Moniker), - Events: ctx.EventManager().Events(), - } - - return &result, nil -} - -// returns the profile with the proper edited fields -// default string is used to let user replace previous inserted values with blank or empty ones -func GetEditedProfile(account types.Profile, msg types.MsgEditProfile) types.Profile { - if msg.NewMoniker != nil { - account.Moniker = *msg.NewMoniker - } - - if msg.Name != nil { - account = account.WithName(msg.Name) - } - - if msg.Surname != nil { - account = account.WithSurname(msg.Surname) - } - - if msg.Bio != nil { - account = account.WithBio(msg.Bio) - } - - if msg.ProfilePic != nil && msg.ProfileCov != nil { - pictures := types.NewPictures(msg.ProfilePic, msg.ProfileCov) - account = account.WithPictures(pictures) - } else { - if msg.ProfilePic != nil && msg.ProfileCov == nil { - account.Pictures.Profile = msg.ProfilePic - } - if msg.ProfileCov != nil && msg.ProfilePic == nil { - account.Pictures.Cover = msg.ProfileCov - } - account = account.WithPictures(account.Pictures) - } - - return account -} - -// handleMsgEditProfile handles the edit of a profile -func handleMsgEditProfile(ctx sdk.Context, keeper Keeper, msg types.MsgEditProfile) (*sdk.Result, error) { - profile, found := keeper.GetProfile(ctx, msg.Creator) - if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("No existent profile to edit for address: %s", msg.Creator)) - } - - profile = GetEditedProfile(profile, msg) err := profile.Validate() if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) @@ -116,11 +47,11 @@ func handleMsgEditProfile(ctx sdk.Context, keeper Keeper, msg types.MsgEditProfi err = keeper.SaveProfile(ctx, profile) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("A profile with moniker: %s has already been created", *msg.NewMoniker)) + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) } createEvent := sdk.NewEvent( - types.EventTypeProfileEdited, + types.EventTypeProfileSaved, sdk.NewAttribute(types.AttributeProfileMoniker, profile.Moniker), sdk.NewAttribute(types.AttributeProfileCreator, profile.Creator.String()), ) diff --git a/x/profile/internal/keeper/handler_test.go b/x/profile/internal/keeper/handler_test.go index b0bb0b7543..29b4bc8aa0 100644 --- a/x/profile/internal/keeper/handler_test.go +++ b/x/profile/internal/keeper/handler_test.go @@ -1,7 +1,6 @@ package keeper_test import ( - "fmt" "testing" "github.com/desmos-labs/desmos/x/profile/internal/keeper" @@ -12,80 +11,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -func Test_handleMsgCreateProfile(t *testing.T) { - tests := []struct { - name string - existentAccount *types.Profile - msg types.MsgCreateProfile - expErr error - }{ - { - name: "Profile already exists", - existentAccount: &testProfile, - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - expErr: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "An account with moniker moniker already exists"), - }, - { - name: "Profile doesnt exists", - existentAccount: nil, - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - expErr: nil, - }, - } - - for _, test := range tests { - test := test - t.Run(test.name, func(t *testing.T) { - ctx, k := SetupTestInput() - store := ctx.KVStore(k.StoreKey) - - if test.existentAccount != nil { - key := types.ProfileStoreKey(test.existentAccount.Creator) - store.Set(key, k.Cdc.MustMarshalBinaryBare(&test.existentAccount)) - k.AssociateMonikerWithAddress(ctx, test.existentAccount.Moniker, test.existentAccount.Creator) - } - - handler := keeper.NewHandler(k) - res, err := handler(ctx, test.msg) - - if res == nil { - require.NotNil(t, err) - require.Equal(t, test.expErr.Error(), err.Error()) - } - if res != nil { - //Check the data - require.Equal(t, k.Cdc.MustMarshalBinaryLengthPrefixed(test.msg.Moniker), res.Data) - - //Check the events - createAccountEv := sdk.NewEvent( - types.EventTypeProfileCreated, - sdk.NewAttribute(types.AttributeProfileMoniker, test.msg.Moniker), - sdk.NewAttribute(types.AttributeProfileCreator, test.msg.Creator.String()), - ) - - require.Len(t, res.Events, 1) - require.Contains(t, res.Events, createAccountEv) - } - - }) - } -} - -func Test_handleMsgEditProfile(t *testing.T) { +func Test_handleMsgSaveProfile(t *testing.T) { editor, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) @@ -108,14 +34,14 @@ func Test_handleMsgEditProfile(t *testing.T) { name string existentAccounts types.Profiles expAccount *types.Profile - msg types.MsgEditProfile + msg types.MsgSaveProfile expErr error }{ { - name: "Profile edited", + name: "Profile saved (with previous profile created)", existentAccounts: types.Profiles{testProfile}, - msg: types.NewMsgEditProfile( - &newMoniker, + msg: types.NewMsgSaveProfile( + newMoniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -126,10 +52,10 @@ func Test_handleMsgEditProfile(t *testing.T) { expErr: nil, }, { - name: "Profile not edited because no profile with given account found", + name: "Profile saved (with no previous profile created)", existentAccounts: nil, - msg: types.NewMsgEditProfile( - &newMoniker, + msg: types.NewMsgSaveProfile( + newMoniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -137,14 +63,13 @@ func Test_handleMsgEditProfile(t *testing.T) { testProfile.Pictures.Cover, testProfile.Creator, ), - expErr: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("No existent profile to edit for address: cosmos1y54exmx84cqtasvjnskf9f63djuuj68p7hqf47")), + expErr: nil, }, { name: "Profile not edited because the new moniker already exists", existentAccounts: types.Profiles{testProfile, testAcc2}, - msg: types.NewMsgEditProfile( - &newMoniker, + msg: types.NewMsgSaveProfile( + newMoniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -157,8 +82,8 @@ func Test_handleMsgEditProfile(t *testing.T) { { name: "Profile not edited because of the invalid pics uri", existentAccounts: types.Profiles{testProfile}, - msg: types.NewMsgEditProfile( - &newMoniker, + msg: types.NewMsgSaveProfile( + newMoniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -197,12 +122,12 @@ func Test_handleMsgEditProfile(t *testing.T) { require.Len(t, profiles, 1) //Check the data - require.Equal(t, k.Cdc.MustMarshalBinaryLengthPrefixed(test.msg.NewMoniker), res.Data) + require.Equal(t, k.Cdc.MustMarshalBinaryLengthPrefixed(test.msg.Moniker), res.Data) //Check the events createAccountEv := sdk.NewEvent( - types.EventTypeProfileEdited, - sdk.NewAttribute(types.AttributeProfileMoniker, *test.msg.NewMoniker), + types.EventTypeProfileSaved, + sdk.NewAttribute(types.AttributeProfileMoniker, test.msg.Moniker), sdk.NewAttribute(types.AttributeProfileCreator, test.msg.Creator.String()), ) @@ -273,115 +198,3 @@ func Test_handleMsgDeleteProfile(t *testing.T) { }) } } - -func TestHandler_GetEditedProfile(t *testing.T) { - name := "mame" - surname := "habe" - bio := "bioh" - pic := "pic" - cov := "cov" - pictures := types.NewPictures(&pic, &cov) - picEdited := types.NewPictures(&pic, testProfile.Pictures.Cover) - covEdited := types.NewPictures(&pic, &cov) - newMoniker := "omn" - - tests := []struct { - name string - profile types.Profile - msg types.MsgEditProfile - expProfile types.Profile - }{ - { - name: "edited profile correctly", - profile: testProfile, - msg: types.NewMsgEditProfile( - &newMoniker, - &name, - &surname, - &bio, - &pic, - &cov, - testProfile.Creator, - ), - expProfile: types.Profile{ - Name: &name, - Surname: &surname, - Moniker: newMoniker, - Bio: &bio, - Pictures: pictures, - Creator: testProfile.Creator, - }, - }, - { - name: "edited profile correctly 2", - profile: testProfile, - msg: types.NewMsgEditProfile( - &newMoniker, - &name, - &surname, - &bio, - &pic, - nil, - testProfile.Creator, - ), - expProfile: types.Profile{ - Name: &name, - Surname: &surname, - Moniker: "omn", - Bio: &bio, - Pictures: picEdited, - Creator: testProfile.Creator, - }, - }, - { - name: "edited profile correctly 3", - profile: testProfile, - msg: types.NewMsgEditProfile( - &newMoniker, - &name, - &surname, - &bio, - nil, - &cov, - testProfile.Creator, - ), - expProfile: types.Profile{ - Name: &name, - Surname: &surname, - Moniker: "omn", - Bio: &bio, - Pictures: covEdited, - Creator: testProfile.Creator, - }, - }, - { - name: "edited profile correctly 4", - profile: testProfile, - msg: types.NewMsgEditProfile( - nil, - &name, - &surname, - &bio, - nil, - &cov, - testProfile.Creator, - ), - expProfile: types.Profile{ - Name: &name, - Surname: &surname, - Moniker: testProfile.Moniker, - Bio: &bio, - Pictures: covEdited, - Creator: testProfile.Creator, - }, - }, - } - - for _, test := range tests { - test := test - t.Run(test.name, func(t *testing.T) { - edited := keeper.GetEditedProfile(test.profile, test.msg) - require.Equal(t, test.expProfile, edited) - }) - } -} diff --git a/x/profile/internal/keeper/invariants_test.go b/x/profile/internal/keeper/invariants_test.go index b5c7b8071f..a69d8a8a29 100644 --- a/x/profile/internal/keeper/invariants_test.go +++ b/x/profile/internal/keeper/invariants_test.go @@ -22,13 +22,13 @@ func TestInvariants(t *testing.T) { }{ { name: "Invariants not violated", - profile: types.NewProfile(moniker, owner), + profile: types.NewProfile(owner).WithMoniker(moniker), expResponse: "Every invariant condition is fulfilled correctly", expBool: true, }, { name: "ValidProfile invariant violated", - profile: types.NewProfile("", owner), + profile: types.NewProfile(owner).WithMoniker(""), expResponse: "profiles: invalid profiles invariant\nThe following list contains invalid profiles:\n Invalid profiles:\n[Moniker]: , [Creator]: cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns\n\n", expBool: true, }, diff --git a/x/profile/internal/keeper/keeper.go b/x/profile/internal/keeper/keeper.go index 8b1c9e451f..93a29f5cf5 100644 --- a/x/profile/internal/keeper/keeper.go +++ b/x/profile/internal/keeper/keeper.go @@ -70,13 +70,13 @@ func (k Keeper) replaceMoniker(ctx sdk.Context, oldMoniker, newMoniker string, c k.AssociateMonikerWithAddress(ctx, newMoniker, creator) } -// SaveProfile allows to save the given account inside the current context. -// It assumes that the given account has already been validated. -// It returns an error if an account with the same moniker from a different creator already exists +// SaveProfile allows to save the given profile inside the current context. +// It assumes that the given profile has already been validated. +// It returns an error if a profile with the same moniker from a different creator already exists func (k Keeper) SaveProfile(ctx sdk.Context, profile types.Profile) error { if addr := k.GetMonikerRelatedAddress(ctx, profile.Moniker); addr != nil && !addr.Equals(profile.Creator) { - return fmt.Errorf("an account with moniker: %s has already been created", profile.Moniker) + return fmt.Errorf("A profile with moniker: %s has already been created", profile.Moniker) } oldMoniker := k.GetMonikerFromAddress(ctx, profile.Creator) @@ -90,8 +90,8 @@ func (k Keeper) SaveProfile(ctx sdk.Context, profile types.Profile) error { return nil } -// DeleteProfile allows to delete an account associated with the given address inside the current context. -// It assumes that the address-related account exists. +// DeleteProfile allows to delete a profile associated with the given address inside the current context. +// It assumes that the address-related profile exists. // nolint: interfacer func (k Keeper) DeleteProfile(ctx sdk.Context, address sdk.AccAddress, moniker string) { store := ctx.KVStore(k.StoreKey) @@ -99,9 +99,9 @@ func (k Keeper) DeleteProfile(ctx sdk.Context, address sdk.AccAddress, moniker s k.DeleteMonikerAddressAssociation(ctx, moniker) } -// GetProfiles returns all the created accounts inside the current context. -func (k Keeper) GetProfiles(ctx sdk.Context) (accounts types.Profiles) { - accounts = make(types.Profiles, 0) +// GetProfiles returns all the created profiles inside the current context. +func (k Keeper) GetProfiles(ctx sdk.Context) (profiles types.Profiles) { + profiles = make(types.Profiles, 0) store := ctx.KVStore(k.StoreKey) iterator := sdk.KVStorePrefixIterator(store, types.ProfileStorePrefix) defer iterator.Close() @@ -109,20 +109,20 @@ func (k Keeper) GetProfiles(ctx sdk.Context) (accounts types.Profiles) { for ; iterator.Valid(); iterator.Next() { var acc types.Profile k.Cdc.MustUnmarshalBinaryBare(iterator.Value(), &acc) - accounts = append(accounts, acc) + profiles = append(profiles, acc) } - return accounts + return profiles } -// GetProfile returns the account corresponding to the given address inside the current context. +// GetProfile returns the profile corresponding to the given address inside the current context. // nolint: interfacer -func (k Keeper) GetProfile(ctx sdk.Context, address sdk.AccAddress) (account types.Profile, found bool) { +func (k Keeper) GetProfile(ctx sdk.Context, address sdk.AccAddress) (profile types.Profile, found bool) { store := ctx.KVStore(k.StoreKey) key := types.ProfileStoreKey(address) if bz := store.Get(key); bz != nil { - k.Cdc.MustUnmarshalBinaryBare(bz, &account) - return account, true + k.Cdc.MustUnmarshalBinaryBare(bz, &profile) + return profile, true } return types.Profile{}, false diff --git a/x/profile/internal/keeper/keeper_test.go b/x/profile/internal/keeper/keeper_test.go index 97771a6ad3..8aa11173d7 100644 --- a/x/profile/internal/keeper/keeper_test.go +++ b/x/profile/internal/keeper/keeper_test.go @@ -132,7 +132,7 @@ func TestKeeper_SaveProfile(t *testing.T) { Creator: creator, }, existentAccounts: types.Profiles{testProfile}, - expError: fmt.Errorf("an account with moniker: moniker has already been created"), + expError: fmt.Errorf("A profile with moniker: moniker has already been created"), }, } diff --git a/x/profile/internal/keeper/utils_functions_test.go b/x/profile/internal/keeper/utils_functions_test.go index 5c845923e3..4b41076f60 100644 --- a/x/profile/internal/keeper/utils_functions_test.go +++ b/x/profile/internal/keeper/utils_functions_test.go @@ -21,10 +21,10 @@ func TestKeeper_IterateProfile(t *testing.T) { require.NoError(t, err) profiles := types.Profiles{ - types.NewProfile("first", creator), - types.NewProfile("second", creator2), - types.NewProfile("not", creator3), - types.NewProfile("third", creator4), + types.NewProfile(creator).WithMoniker("first"), + types.NewProfile(creator2).WithMoniker("second"), + types.NewProfile(creator3).WithMoniker("not"), + types.NewProfile(creator4).WithMoniker("third"), } expProfiles := types.Profiles{ diff --git a/x/profile/internal/simulation/operations.go b/x/profile/internal/simulation/operations.go index 4e3d60039b..d2acecebbb 100644 --- a/x/profile/internal/simulation/operations.go +++ b/x/profile/internal/simulation/operations.go @@ -12,8 +12,7 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgCreateProfile = "op_weight_msg_create_profile" - OpWeightMsgEditProfile = "op_weight_msg_edit_profile" + OpWeightMsgSaveProfile = "op_weight_msg_save_profile" OpWeightMsgDeleteProfile = "op_weight_msg_delete_profile" DefaultGasValue = 200000 @@ -21,17 +20,10 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations(appParams sim.AppParams, cdc *codec.Codec, k keeper.Keeper, ak auth.AccountKeeper) sim.WeightedOperations { - var weightMsgCreateProfile int - appParams.GetOrGenerate(cdc, OpWeightMsgCreateProfile, &weightMsgCreateProfile, nil, + var weightMsgSaveProfile int + appParams.GetOrGenerate(cdc, OpWeightMsgSaveProfile, &weightMsgSaveProfile, nil, func(_ *rand.Rand) { - weightMsgCreateProfile = params.DefaultWeightMsgCreateAccount - }, - ) - - var weightMsgEditProfile int - appParams.GetOrGenerate(cdc, OpWeightMsgEditProfile, &weightMsgEditProfile, nil, - func(_ *rand.Rand) { - weightMsgEditProfile = params.DefaultWeightMsgEditAccount + weightMsgSaveProfile = params.DefaultWeightMsgSaveAccount }, ) @@ -44,12 +36,8 @@ func WeightedOperations(appParams sim.AppParams, cdc *codec.Codec, k keeper.Keep return sim.WeightedOperations{ sim.NewWeightedOperation( - weightMsgCreateProfile, - SimulateMsgCreateProfile(ak), - ), - sim.NewWeightedOperation( - weightMsgEditProfile, - SimulateMsgEditProfile(k, ak), + weightMsgSaveProfile, + SimulateMsgSaveProfile(k, ak), ), sim.NewWeightedOperation( weightMsgDeleteProfile, diff --git a/x/profile/internal/simulation/operations_profile.go b/x/profile/internal/simulation/operations_profile.go index 0115551172..5f10f39b03 100644 --- a/x/profile/internal/simulation/operations_profile.go +++ b/x/profile/internal/simulation/operations_profile.go @@ -14,97 +14,14 @@ import ( sim "github.com/cosmos/cosmos-sdk/x/simulation" ) -// SimulateMsgCreateProfile tests and runs a single msg create profile where the creator already exists +// SimulateMsgSaveProfile tests and runs a single msg save profile where the creator already exists // nolint: funlen -func SimulateMsgCreateProfile(ak auth.AccountKeeper) sim.Operation { +func SimulateMsgSaveProfile(k keeper.Keeper, ak auth.AccountKeeper) sim.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []sim.Account, chainID string, ) (OperationMsg sim.OperationMsg, futureOps []sim.FutureOperation, err error) { - data, skip, err := randomCreateProfileFields(r, ctx, accs, ak) - if err != nil { - return sim.NoOpMsg(types.ModuleName), nil, err - } - - if skip { - return sim.NoOpMsg(types.ModuleName), nil, nil - } - - msg := types.NewMsgCreateProfile( - data.Moniker, - &data.Name, - &data.Surname, - &data.Bio, - &data.Picture, - data.Creator.Address, - ) - - err = sendMsgCreateProfile(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{data.Creator.PrivKey}) - if err != nil { - return sim.NoOpMsg(types.ModuleName), nil, err - } - - return sim.NewOperationMsg(msg, true, ""), nil, nil - } -} - -// sendMsgCreateProfile sends a transaction with a MsgCreateProfile from a provided random profile. -func sendMsgCreateProfile( - r *rand.Rand, app *baseapp.BaseApp, ak auth.AccountKeeper, - msg types.MsgCreateProfile, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, -) error { - - account := ak.GetAccount(ctx, msg.Creator) - coins := account.SpendableCoins(ctx.BlockTime()) - - fees, err := sim.RandomFees(r, ctx, coins) - if err != nil { - return err - } - - tx := helpers.GenTx( - []sdk.Msg{msg}, - fees, - DefaultGasValue, - chainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - privkeys..., - ) - - _, _, err = app.Deliver(tx) - if err != nil { - return err - } - return nil -} - -// randomCreateProfileFields returns random profile data -func randomCreateProfileFields(r *rand.Rand, ctx sdk.Context, accs []sim.Account, ak auth.AccountKeeper, -) (*ProfileData, bool, error) { - if len(accs) == 0 { - return nil, true, nil - } - - accountData := RandomProfileData(r, accs) - acc := ak.GetAccount(ctx, accountData.Creator.Address) - - // Skip the operation without error as the profile is not valid - if acc == nil { - return nil, true, nil - } - - return &accountData, false, nil -} - -// SimulateMsgEditProfile tests and runs a single msg edit profile where the creator already exists -// nolint: funlen -func SimulateMsgEditProfile(k keeper.Keeper, ak auth.AccountKeeper) sim.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, - accs []sim.Account, chainID string, - ) (OperationMsg sim.OperationMsg, futureOps []sim.FutureOperation, err error) { - - acc, data, newMoniker, skip, err := randomProfileEditFields(r, ctx, accs, k, ak) + acc, data, newMoniker, skip, err := randomProfileSaveFields(r, ctx, accs, k) if err != nil { return sim.NoOpMsg(types.ModuleName), nil, err } @@ -113,8 +30,8 @@ func SimulateMsgEditProfile(k keeper.Keeper, ak auth.AccountKeeper) sim.Operatio return sim.NoOpMsg(types.ModuleName), nil, nil } - msg := types.NewMsgEditProfile( - &newMoniker, + msg := types.NewMsgSaveProfile( + newMoniker, data.Name, data.Surname, data.Bio, @@ -123,7 +40,7 @@ func SimulateMsgEditProfile(k keeper.Keeper, ak auth.AccountKeeper) sim.Operatio acc.Address, ) - err = sendMsgEditProfile(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{acc.PrivKey}) + err = sendMsgSaveProfile(r, app, ak, msg, ctx, chainID, []crypto.PrivKey{acc.PrivKey}) if err != nil { return sim.NoOpMsg(types.ModuleName), nil, err } @@ -132,10 +49,10 @@ func SimulateMsgEditProfile(k keeper.Keeper, ak auth.AccountKeeper) sim.Operatio } } -// sendMsgEditProfile sends a transaction with a MsgEditProfile from a provided random profile. -func sendMsgEditProfile( +// sendMsgSaveProfile sends a transaction with a MsgSaveProfile from a provided random profile. +func sendMsgSaveProfile( r *rand.Rand, app *baseapp.BaseApp, ak auth.AccountKeeper, - msg types.MsgEditProfile, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, + msg types.MsgSaveProfile, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, ) error { account := ak.GetAccount(ctx, msg.Creator) @@ -164,9 +81,9 @@ func sendMsgEditProfile( return nil } -// randomProfileEditFields returns random profile data -func randomProfileEditFields( - r *rand.Rand, ctx sdk.Context, accs []sim.Account, k keeper.Keeper, ak auth.AccountKeeper, +// randomProfileSaveFields returns random profile data +func randomProfileSaveFields( + r *rand.Rand, ctx sdk.Context, accs []sim.Account, k keeper.Keeper, ) (sim.Account, types.Profile, string, bool, error) { if len(accs) == 0 { return sim.Account{}, types.Profile{}, "", true, nil diff --git a/x/profile/internal/types/codec.go b/x/profile/internal/types/codec.go index c5866e1ead..c068bc5bef 100644 --- a/x/profile/internal/types/codec.go +++ b/x/profile/internal/types/codec.go @@ -10,7 +10,6 @@ func init() { } func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgCreateProfile{}, "desmos/MsgCreateProfile", nil) - cdc.RegisterConcrete(MsgEditProfile{}, "desmos/MsgEditProfile", nil) + cdc.RegisterConcrete(MsgSaveProfile{}, "desmos/MsgSaveProfile", nil) cdc.RegisterConcrete(MsgDeleteProfile{}, "desmos/MsgDeleteProfile", nil) } diff --git a/x/profile/internal/types/events.go b/x/profile/internal/types/events.go index 0a68e2149a..dfc2d5263d 100644 --- a/x/profile/internal/types/events.go +++ b/x/profile/internal/types/events.go @@ -1,8 +1,7 @@ package types const ( - EventTypeProfileCreated = "profile_created" - EventTypeProfileEdited = "profile_edited" + EventTypeProfileSaved = "profile_saved" EventTypeProfileDeleted = "profile_deleted" // Profile attributes diff --git a/x/profile/internal/types/keys.go b/x/profile/internal/types/keys.go index c956933cc9..442a908725 100644 --- a/x/profile/internal/types/keys.go +++ b/x/profile/internal/types/keys.go @@ -13,11 +13,11 @@ const ( MinNameSurnameLength = 2 MaxNameSurnameLength = 500 + MinMonikerLength = 2 MaxMonikerLength = 30 MaxBioLength = 1000 - ActionCreateProfile = "create_profile" - ActionEditProfile = "edit_profile" + ActionSaveProfile = "save_profile" ActionDeleteProfile = "delete_profile" //Queries diff --git a/x/profile/internal/types/msgs.go b/x/profile/internal/types/msgs.go index cffd432a76..5e40fd4747 100644 --- a/x/profile/internal/types/msgs.go +++ b/x/profile/internal/types/msgs.go @@ -2,109 +2,18 @@ package types import ( "fmt" - "strings" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // ---------------------- -// --- MsgCreateProfile +// --- MsgSaveProfile // ---------------------- -// MsgCreateProfile defines a CreateProfile message -type MsgCreateProfile struct { - Moniker string `json:"moniker" yaml:"moniker"` - Name *string `json:"name,omitempty" yaml:"name,omitempty"` - Surname *string `json:"surname,omitempty" yaml:"surname,omitempty"` - Bio *string `json:"bio,omitempty" yaml:"bio,omitempty"` - Pictures *Pictures `json:"pictures,omitempty" yaml:"pictures,omitempty"` - Creator sdk.AccAddress `json:"creator" yaml:"creator"` -} - -// NewMsgCreateProfile is a constructor function for MsgCreateProfile -func NewMsgCreateProfile(moniker string, name, surname, bio *string, pictures *Pictures, - creator sdk.AccAddress) MsgCreateProfile { - return MsgCreateProfile{ - Moniker: moniker, - Name: name, - Surname: surname, - Bio: bio, - Pictures: pictures, - Creator: creator, - } -} - -// Route should return the name of the module -func (msg MsgCreateProfile) Route() string { return RouterKey } - -// Type should return the action -func (msg MsgCreateProfile) Type() string { return ActionCreateProfile } - -// ValidateBasic runs stateless checks on the message -func (msg MsgCreateProfile) ValidateBasic() error { - if msg.Creator.Empty() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf("Invalid creator address: %s", msg.Creator)) - } - - if msg.Name != nil { - if len(*msg.Name) < MinNameSurnameLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile name cannot be less than %d characters", MinNameSurnameLength)) - } - - if len(*msg.Name) > MaxNameSurnameLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile name cannot exceed %d characters", MaxNameSurnameLength)) - } - } - - if msg.Surname != nil { - if msg.Surname != nil && len(*msg.Surname) < MinNameSurnameLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile surname cannot be less than %d characters", MinNameSurnameLength)) - } - - if len(*msg.Surname) > MaxNameSurnameLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile surname cannot exceed %d characters", MaxNameSurnameLength)) - } - } - - if len(strings.TrimSpace(msg.Moniker)) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile moniker cannot be blank or empty") - } - - if len(msg.Moniker) > MaxMonikerLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile moniker cannot exceed %d characters", MaxMonikerLength)) - } - - if msg.Bio != nil && len(*msg.Bio) > MaxBioLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile biography cannot exceed %d characters", MaxBioLength)) - } - - if msg.Pictures != nil { - if err := msg.Pictures.Validate(); err != nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) - } - } - - return nil -} - -// GetSignBytes encodes the message for signing -func (msg MsgCreateProfile) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) -} - -// GetSigners defines whose signature is required -func (msg MsgCreateProfile) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.Creator} -} - -// ---------------------- -// --- MsgEditProfile -// ---------------------- - -// MsgEditProfile defines a EditProfile message -type MsgEditProfile struct { - NewMoniker *string `json:"new_moniker" yaml:"new_moniker"` +// MsgSaveProfile defines a SaveProfile message +type MsgSaveProfile struct { + Moniker string `json:"moniker" yaml:"moniker"` Name *string `json:"name,omitempty" yaml:"name,omitempty"` Surname *string `json:"surname,omitempty" yaml:"surname,omitempty"` Bio *string `json:"bio,omitempty" yaml:"bio,omitempty"` @@ -113,11 +22,11 @@ type MsgEditProfile struct { Creator sdk.AccAddress `json:"creator" yaml:"creator"` } -// NewMsgEditProfile is a constructor function for MsgEditProfile -func NewMsgEditProfile(newMoniker, name, surname, bio, profilePic, - profileCov *string, creator sdk.AccAddress) MsgEditProfile { - return MsgEditProfile{ - NewMoniker: newMoniker, +// NewMsgSaveProfile is a constructor function for MsgSaveProfile +func NewMsgSaveProfile(moniker string, name, surname, bio, profilePic, + profileCov *string, creator sdk.AccAddress) MsgSaveProfile { + return MsgSaveProfile{ + Moniker: moniker, Name: name, Surname: surname, Bio: bio, @@ -128,19 +37,23 @@ func NewMsgEditProfile(newMoniker, name, surname, bio, profilePic, } // Route should return the name of the module -func (msg MsgEditProfile) Route() string { return RouterKey } +func (msg MsgSaveProfile) Route() string { return RouterKey } // Type should return the action -func (msg MsgEditProfile) Type() string { return ActionEditProfile } +func (msg MsgSaveProfile) Type() string { return ActionSaveProfile } // ValidateBasic runs stateless checks on the message -func (msg MsgEditProfile) ValidateBasic() error { +func (msg MsgSaveProfile) ValidateBasic() error { if msg.Creator.Empty() { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf("Invalid creator address: %s", msg.Creator)) } - if msg.NewMoniker != nil && len(*msg.NewMoniker) > MaxMonikerLength { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile new moniker cannot exceed %d characters", MaxMonikerLength)) + if len(msg.Moniker) < MinMonikerLength { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile moniker cannot be less than %d characters", MinMonikerLength)) + } + + if len(msg.Moniker) > MaxMonikerLength { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("Profile moniker cannot exceed %d characters", MaxMonikerLength)) } if msg.Name != nil { @@ -171,12 +84,12 @@ func (msg MsgEditProfile) ValidateBasic() error { } // GetSignBytes encodes the message for signing -func (msg MsgEditProfile) GetSignBytes() []byte { +func (msg MsgSaveProfile) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } // GetSigners defines whose signature is required -func (msg MsgEditProfile) GetSigners() []sdk.AccAddress { +func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Creator} } diff --git a/x/profile/internal/types/msgs_test.go b/x/profile/internal/types/msgs_test.go index 28b6b2f50b..e3c423f707 100644 --- a/x/profile/internal/types/msgs_test.go +++ b/x/profile/internal/types/msgs_test.go @@ -11,7 +11,7 @@ import ( ) // ---------------------- -// --- MsgCreateProfile +// --- MsgSaveProfile // ---------------------- var testProfileOwner, _ = sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") @@ -22,8 +22,6 @@ var name = "name" var surname = "surname" var bio = "biography" -var invalidProfilePic = "adnX3" -var invalidPics = types.NewPictures(&invalidProfilePic, &testCoverPic) var invalidMaxLenField = "9YfrVVi3UEI1ymN7n6isScyHNSt30xG6Jn1EDxEXxWOn0voSMIKqLhHsBfnZoXEXeFlAO5qMwjNGvgoiNBtoMfR78J2SNhBz" + "wNxlTky9DCJ2F2luh9cTc7umcHl2BDwSepE1Iijn4htrP7vcKWgIgHYh73oNmF7PTiU1gmL2G8W4XB06bpDLFb0eLzPbSGLe51" + "25k9tljhFBdgSPtoKuLQUQPGC3IqyyTIqQEpLeNpmbiJUDmbqQ1tyyS8mDC7WQEYv8uuYU90pjBSkGJQs2FI2Q7hIHL202O1SF" + @@ -52,18 +50,9 @@ var testProfile = types.Profile{ Creator: testProfileOwner, } -var msgCreateProfile = types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, -) - var newMoniker = "monk" -var msgEditProfile = types.NewMsgEditProfile( - &newMoniker, +var msgEditProfile = types.NewMsgSaveProfile( + newMoniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -76,208 +65,27 @@ var msgDeleteProfile = types.NewMsgDeleteProfile( testProfile.Creator, ) -func TestMsgCreateProfile_Route(t *testing.T) { - actual := msgCreateProfile.Route() - require.Equal(t, "profiles", actual) -} - -func TestMsgCreateProfile_Type(t *testing.T) { - actual := msgCreateProfile.Type() - require.Equal(t, "create_profile", actual) -} - -func TestMsgCreateProfile_ValidateBasic(t *testing.T) { - - tests := []struct { - name string - msg types.MsgCreateProfile - error error - }{ - { - name: "Empty owner returns error", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - nil, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "Invalid creator address: "), - }, - { - name: "Max name length exceeded", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - &invalidMaxLenField, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile name cannot exceed 500 characters"), - }, - { - name: "Min name length not reached", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - &invalidMinLenField, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile name cannot be less than 2 characters"), - }, - { - name: "Min surname length not reached", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - &invalidMinLenField, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile surname cannot be less than 2 characters"), - }, - { - name: "Max surname length exceeded", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - &invalidMaxLenField, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile surname cannot exceed 500 characters"), - }, - { - name: "Max bio length exceeded", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - &invalidBio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile biography cannot exceed 1000 characters"), - }, - { - name: "Empty moniker error", - msg: types.NewMsgCreateProfile( - "", - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile moniker cannot be blank or empty"), - }, - { - name: "Max moniker length exceeded", - msg: types.NewMsgCreateProfile( - "asdserhrtyjeqrgdfhnr1asdserhrtyjeqrgdfhnr1", - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile moniker cannot exceed 30 characters"), - }, - { - name: "Invalid pictures uri", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - invalidPics, - testProfile.Creator, - ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "invalid profile picture uri provided"), - }, - { - name: "No error message", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - testProfile.Pictures, - testProfile.Creator, - ), - error: nil, - }, - { - name: "No error message with nil pics", - msg: types.NewMsgCreateProfile( - testProfile.Moniker, - testProfile.Name, - testProfile.Surname, - testProfile.Bio, - nil, - testProfile.Creator, - ), - error: nil, - }, - } - - for _, test := range tests { - test := test - t.Run(test.name, func(t *testing.T) { - returnedError := test.msg.ValidateBasic() - if test.error == nil { - require.Nil(t, returnedError) - } else { - require.NotNil(t, returnedError) - require.Equal(t, test.error.Error(), returnedError.Error()) - } - }) - } -} - -func TestMsgCreateProfile_GetSignBytes(t *testing.T) { - actual := msgCreateProfile.GetSignBytes() - expected := `{"type":"desmos/MsgCreateProfile","value":{"bio":"biography","creator":"cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns","moniker":"moniker","name":"name","pictures":{"cover":"https://shorturl.at/cgpyF","profile":"https://shorturl.at/adnX3"},"surname":"surname"}}` - require.Equal(t, expected, string(actual)) -} - -func TestMsgCreateProfile_GetSigners(t *testing.T) { - actual := msgCreateProfile.GetSigners() - require.Equal(t, 1, len(actual)) - require.Equal(t, msgCreateProfile.Creator, actual[0]) -} - -// ---------------------- -// --- MsgEditProfile -// ---------------------- - -func TestMsgEditProfile_Route(t *testing.T) { +func TestMsgSaveProfile_Route(t *testing.T) { actual := msgEditProfile.Route() require.Equal(t, "profiles", actual) } -func TestMsgEditProfile_Type(t *testing.T) { +func TestMsgSaveProfile_Type(t *testing.T) { actual := msgEditProfile.Type() - require.Equal(t, "edit_profile", actual) + require.Equal(t, "save_profile", actual) } -func TestMsgEditProfile_ValidateBasic(t *testing.T) { +func TestMsgSaveProfile_ValidateBasic(t *testing.T) { invalidMonikerLen := "asdserhrtyjeqrgdfhnr1asdserhrtyjeqrgdfhnr1" tests := []struct { name string - msg types.MsgEditProfile + msg types.MsgSaveProfile error error }{ { name: "Empty owner returns error", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -289,8 +97,8 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { }, { name: "Max name length exceeded", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, &invalidMaxLenField, testProfile.Surname, testProfile.Bio, @@ -302,8 +110,8 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { }, { name: "Min name length not reached", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, &invalidMinLenField, testProfile.Surname, testProfile.Bio, @@ -315,8 +123,8 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { }, { name: "Max surname length exceeded", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, testProfile.Name, &invalidMaxLenField, testProfile.Bio, @@ -328,8 +136,8 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { }, { name: "Min surname length not reached", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, testProfile.Name, &invalidMinLenField, testProfile.Bio, @@ -341,8 +149,8 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { }, { name: "Max bio length exceeded", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, testProfile.Name, testProfile.Surname, &invalidBio, @@ -353,9 +161,22 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile biography cannot exceed 1000 characters"), }, { - name: "Max new moniker length exceeded", - msg: types.NewMsgEditProfile( - &invalidMonikerLen, + name: "Min moniker length not reached", + msg: types.NewMsgSaveProfile( + "l", + testProfile.Name, + testProfile.Surname, + testProfile.Bio, + testProfile.Pictures.Profile, + testProfile.Pictures.Cover, + testProfile.Creator, + ), + error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile moniker cannot be less than 2 characters"), + }, + { + name: "Max moniker length exceeded", + msg: types.NewMsgSaveProfile( + invalidMonikerLen, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -363,12 +184,12 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { testProfile.Pictures.Cover, testProfile.Creator, ), - error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile new moniker cannot exceed 30 characters"), + error: sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Profile moniker cannot exceed 30 characters"), }, { name: "No error message", - msg: types.NewMsgEditProfile( - &testProfile.Moniker, + msg: types.NewMsgSaveProfile( + testProfile.Moniker, testProfile.Name, testProfile.Surname, testProfile.Bio, @@ -394,13 +215,13 @@ func TestMsgEditProfile_ValidateBasic(t *testing.T) { } } -func TestMsgEditProfile_GetSignBytes(t *testing.T) { +func TestMsgSaveProfile_GetSignBytes(t *testing.T) { actual := msgEditProfile.GetSignBytes() - expected := `{"type":"desmos/MsgEditProfile","value":{"bio":"biography","creator":"cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns","name":"name","new_moniker":"monk","profile_cov":"https://shorturl.at/cgpyF","profile_pic":"https://shorturl.at/adnX3","surname":"surname"}}` + expected := `{"type":"desmos/MsgSaveProfile","value":{"bio":"biography","creator":"cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns","moniker":"monk","name":"name","profile_cov":"https://shorturl.at/cgpyF","profile_pic":"https://shorturl.at/adnX3","surname":"surname"}}` require.Equal(t, expected, string(actual)) } -func TestMsgEditProfile_GetSigners(t *testing.T) { +func TestMsgSaveProfile_GetSigners(t *testing.T) { actual := msgEditProfile.GetSigners() require.Equal(t, 1, len(actual)) require.Equal(t, msgEditProfile.Creator, actual[0]) diff --git a/x/profile/internal/types/pictures.go b/x/profile/internal/types/pictures.go index cb9642ca5d..5cca0e6c77 100644 --- a/x/profile/internal/types/pictures.go +++ b/x/profile/internal/types/pictures.go @@ -12,6 +12,9 @@ type Pictures struct { // NewPictures is a constructor function for Pictures func NewPictures(profile, cover *string) *Pictures { + if profile == nil && cover == nil { + return nil + } return &Pictures{ Profile: profile, Cover: cover, @@ -24,26 +27,17 @@ func (pic Pictures) Equals(otherPic *Pictures) bool { pic.Cover == otherPic.Cover } -// ValidateURI checks if the given uri string is well-formed according to the regExp and return and error otherwise -func ValidateURI(uri string) error { - if !URIRegEx.MatchString(uri) { - return fmt.Errorf("invalid uri provided") - } - - return nil -} - // Validate check the validity of the Pictures func (pic Pictures) Validate() error { if pic.Profile != nil { - if err := ValidateURI(*pic.Profile); err != nil { + if valid := URIRegEx.MatchString(*pic.Profile); !valid { return fmt.Errorf("invalid profile picture uri provided") } } if pic.Cover != nil { - if err := ValidateURI(*pic.Cover); err != nil { + if valid := URIRegEx.MatchString(*pic.Cover); !valid { return fmt.Errorf("invalid profile cover uri provided") } } diff --git a/x/profile/internal/types/profile.go b/x/profile/internal/types/profile.go index cac8006c83..076e661d75 100644 --- a/x/profile/internal/types/profile.go +++ b/x/profile/internal/types/profile.go @@ -18,13 +18,18 @@ type Profile struct { Creator sdk.AccAddress `json:"creator" yaml:"creator"` } -func NewProfile(moniker string, creator sdk.AccAddress) Profile { +func NewProfile(creator sdk.AccAddress) Profile { return Profile{ - Moniker: moniker, Creator: creator, } } +//WithMoniker updates profile's moniker with the given one +func (profile Profile) WithMoniker(moniker string) Profile { + profile.Moniker = moniker + return profile +} + // WithSurname updates profile's name with the given one func (profile Profile) WithName(name *string) Profile { profile.Name = name @@ -44,8 +49,8 @@ func (profile Profile) WithBio(bio *string) Profile { } // WithPicture updates profile's pictures with the given one -func (profile Profile) WithPictures(pictures *Pictures) Profile { - profile.Pictures = pictures +func (profile Profile) WithPictures(profilePic, coverPic *string) Profile { + profile.Pictures = NewPictures(profilePic, coverPic) return profile } diff --git a/x/profile/internal/types/profile_test.go b/x/profile/internal/types/profile_test.go index 12820d4378..9cb961ed03 100644 --- a/x/profile/internal/types/profile_test.go +++ b/x/profile/internal/types/profile_test.go @@ -12,18 +12,27 @@ import ( func TestNewProfile(t *testing.T) { owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) - moniker := "monik" - expProfile := types.Profile{Moniker: moniker, Creator: owner} - actProfile := types.NewProfile(moniker, owner) + expProfile := types.Profile{Creator: owner} + actProfile := types.NewProfile(owner) require.Equal(t, expProfile, actProfile) } +func TestProfile_WithMoniker(t *testing.T) { + owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") + require.NoError(t, err) + profile := types.NewProfile(owner) + + profileWithMoniker := profile.WithMoniker("monik") + + require.Equal(t, types.NewProfile(owner).WithMoniker("monik"), profileWithMoniker) +} + func TestProfile_WithName(t *testing.T) { owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) moniker := "monik" - profile := types.NewProfile(moniker, owner) + profile := types.NewProfile(owner).WithMoniker(moniker) name := "name" tests := []struct { @@ -53,7 +62,7 @@ func TestProfile_WithSurname(t *testing.T) { owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) moniker := "monker" - profile := types.NewProfile(moniker, owner) + profile := types.NewProfile(owner).WithMoniker(moniker) surname := "surname" tests := []struct { @@ -83,7 +92,7 @@ func TestProfile_WithBio(t *testing.T) { owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) moniker := "moniker" - profile := types.NewProfile(moniker, owner) + profile := types.NewProfile(owner).WithMoniker(moniker) bio := "surname" tests := []struct { @@ -113,27 +122,29 @@ func TestProfile_WithPics(t *testing.T) { owner, err := sdk.AccAddressFromBech32("cosmos1cjf97gpzwmaf30pzvaargfgr884mpp5ak8f7ns") require.NoError(t, err) moniker := "moniker" - profile := types.NewProfile(moniker, owner) + profile := types.NewProfile(owner).WithMoniker(moniker) var pic = "profile" var cov = "cover" - pics := types.NewPictures(&pic, &cov) tests := []struct { name string profile types.Profile - pics *types.Pictures + pic *string + cov *string expProfile types.Profile }{ { name: "not nil pics", profile: profile, - pics: pics, - expProfile: types.Profile{Moniker: moniker, Creator: owner, Pictures: pics}, + pic: &pic, + cov: &cov, + expProfile: types.Profile{Moniker: moniker, Creator: owner, Pictures: types.NewPictures(&pic, &cov)}, }, { name: "nil pics", profile: profile, - pics: nil, + pic: nil, + cov: nil, expProfile: types.Profile{Moniker: moniker, Creator: owner}, }, } @@ -141,7 +152,7 @@ func TestProfile_WithPics(t *testing.T) { for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { - actProf := test.profile.WithPictures(test.pics) + actProf := test.profile.WithPictures(test.pic, test.cov) require.Equal(t, test.expProfile, actProf) }) }