-
Notifications
You must be signed in to change notification settings - Fork 44
/
models.go
920 lines (766 loc) · 23.5 KB
/
models.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
package types
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/gogo/protobuf/proto"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/rivo/uniseg"
)
// ParsePostID parses the given value as a post id, returning an error if it's invalid
func ParsePostID(value string) (uint64, error) {
if value == "" {
return 0, nil
}
postID, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid post id: %s", err)
}
return postID, nil
}
// NewPost allows to build a new Post instance
func NewPost(
subspaceID uint64,
sectionID uint32,
id uint64,
externalID string,
text string,
author string,
conversationID uint64,
entities *Entities,
tags []string,
referencedPosts []PostReference,
replySetting ReplySetting,
creationDate time.Time,
lastEditedDate *time.Time,
owner string,
) Post {
return Post{
SubspaceID: subspaceID,
SectionID: sectionID,
ID: id,
ExternalID: externalID,
Text: text,
Entities: entities,
Tags: tags,
Author: author,
ConversationID: conversationID,
ReferencedPosts: referencedPosts,
ReplySettings: replySetting,
CreationDate: creationDate,
LastEditedDate: lastEditedDate,
Owner: owner,
}
}
// Validate implements fmt.Validator
func (p Post) Validate() error {
if p.SubspaceID == 0 {
return fmt.Errorf("invalid subspace id: %d", p.SubspaceID)
}
if p.ID == 0 {
return fmt.Errorf("invalid post id: %d", p.ID)
}
if p.Entities != nil {
err := p.Entities.Validate()
if err != nil {
return fmt.Errorf("invalid entities: %s", err)
}
}
for _, tag := range p.Tags {
if strings.TrimSpace(tag) == "" {
return fmt.Errorf("invalid post tag: %s", tag)
}
}
_, err := sdk.AccAddressFromBech32(p.Author)
if err != nil {
return fmt.Errorf("invalid author address: %s", err)
}
if p.ConversationID >= p.ID {
return fmt.Errorf("invalid conversation id: %d", p.ConversationID)
}
for _, reference := range p.ReferencedPosts {
err = reference.Validate()
if err != nil {
return fmt.Errorf("invalid post reference: %s", err)
}
if reference.PostID >= p.ID {
return fmt.Errorf("invalid referenced post id: %d", reference.PostID)
}
}
if p.ReplySettings == REPLY_SETTING_UNSPECIFIED {
return fmt.Errorf("invalid reply setting: %s", p.ReplySettings)
}
if p.CreationDate.IsZero() {
return fmt.Errorf("invalid post creation date: %s", err)
}
if p.LastEditedDate != nil {
// Instead of zero, we should use nil
if p.LastEditedDate.IsZero() {
return fmt.Errorf("invalid post last edited date: %s", err)
}
// Make sure the creation date is always before the last edit date
if p.LastEditedDate.Before(p.CreationDate) {
return fmt.Errorf("last edited date cannot be before the creation date")
}
}
_, err = sdk.AccAddressFromBech32(p.Owner)
if err != nil {
return fmt.Errorf("invalid owner address: %s", err)
}
return nil
}
// IsUserMentioned tells whether the given user is mentioned inside the post or not
func (p Post) IsUserMentioned(user string) bool {
for _, mention := range p.GetMentionedUsers() {
if mention == user {
return true
}
}
return false
}
// GetMentionedUsers returns all the mentioned users
func (p Post) GetMentionedUsers() []string {
if p.Entities == nil {
return nil
}
mentions := make([]string, len(p.Entities.Mentions))
for i, mention := range p.Entities.Mentions {
mentions[i] = mention.Tag
}
return mentions
}
// GetTextLength returns the length of the post text
func (p Post) GetTextLength() int {
// Counting graphemes instead of runes of bytes can provide a more accurate length of the text.
// This will also ensure that emojis are counted as a single character, which will grant a more consistent
// user experience with clients as well.
// Example: 🏳️🌈 (rainbow flag emoji) is 1 grapheme, 4 runes, and 14 bytes.
return uniseg.GraphemeClusterCount(p.Text)
}
// NewPostReference returns a new PostReference instance
func NewPostReference(referenceType PostReferenceType, postID uint64, position uint64) PostReference {
return PostReference{
Type: referenceType,
PostID: postID,
Position: position,
}
}
// Validate implements fmt.Validator
func (r PostReference) Validate() error {
if r.Type == POST_REFERENCE_TYPE_UNSPECIFIED {
return fmt.Errorf("invalid reference type: %s", r.Type)
}
if r.PostID == 0 {
return fmt.Errorf("invalid post id: %d", r.PostID)
}
if r.Type != POST_REFERENCE_TYPE_QUOTE && r.Position > 0 {
return fmt.Errorf("reference position should be set only with POST_REFERENCE_TYPE_QUOTE")
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// PostUpdate contains all the data that can be updated about a post.
// When performing an update, if a text field should not be edited then it must be set to types.DoNotModify.
type PostUpdate struct {
// If it shouldn't replace the current text, it must be set to types.DoNotModify
Text string
// Update's entities will always replace the existing ones
Entities *Entities
// Update's tags will always replace the existing ones
Tags []string
UpdateTime time.Time
}
// NewPostUpdate returns a new PostUpdate instance
func NewPostUpdate(text string, entities *Entities, tags []string, updateTime time.Time) PostUpdate {
return PostUpdate{
Text: text,
Entities: entities,
Tags: tags,
UpdateTime: updateTime,
}
}
// Update updates the fields of a given post without validating it.
// Before storing the updated post, a validation with keeper.ValidatePost should
// be performed.
func (p Post) Update(update PostUpdate) Post {
if update.Text == DoNotModify {
update.Text = p.Text
}
return NewPost(
p.SubspaceID,
p.SectionID,
p.ID,
p.ExternalID,
update.Text,
p.Author,
p.ConversationID,
update.Entities,
update.Tags,
p.ReferencedPosts,
p.ReplySettings,
p.CreationDate,
&update.UpdateTime,
p.Owner,
)
}
// --------------------------------------------------------------------------------------------------------------------
// PostMove contains data related to a post that can be updated after it has been moved.
type PostMove struct {
// ID of the subspace where the post should be moved to
SubspaceID uint64
// ID of the section where the post should be moved to
SectionID uint32
// ID of the post within the new subspace
PostID uint64
UpdateTime time.Time
}
// NewPostMove returns a new PostMove instance
func NewPostMove(subspaceID uint64, sectionID uint32, postID uint64, updateTime time.Time) PostMove {
return PostMove{
SubspaceID: subspaceID,
SectionID: sectionID,
PostID: postID,
UpdateTime: updateTime,
}
}
// Update updates the fields of a moved post without validating it.
// Before storing the updated post, a validation with keeper.ValidatePost should
// be performed.
func (update PostMove) Update(post Post) Post {
return NewPost(
update.SubspaceID,
update.SectionID,
update.PostID,
post.ExternalID,
post.Text,
post.Author,
0,
post.Entities,
post.Tags,
nil,
post.ReplySettings,
post.CreationDate,
&update.UpdateTime,
post.Owner,
)
}
// --------------------------------------------------------------------------------------------------------------------
// OwnerTransfer contains data related to a post that can be updated after the owner of it has been transferred.
type OwnerTransfer struct {
// Address of the user who will be the new owner of the post
NewOwner string
UpdateTime time.Time
}
// NewOwnerTransfer returns a new OwnerTransfer instance
func NewOwnerTransfer(newOwner string, updateTime time.Time) OwnerTransfer {
return OwnerTransfer{
NewOwner: newOwner,
UpdateTime: updateTime,
}
}
// Update updates the fields of a owner transferred post without validating it.
// Before storing the updated post, a validation with keeper.ValidatePost should
// be performed.
func (update OwnerTransfer) Update(post Post) Post {
return NewPost(
post.SubspaceID,
post.SectionID,
post.ID,
post.ExternalID,
post.Text,
post.Author,
post.ConversationID,
post.Entities,
post.Tags,
post.ReferencedPosts,
post.ReplySettings,
post.CreationDate,
&update.UpdateTime,
update.NewOwner,
)
}
// --------------------------------------------------------------------------------------------------------------------
// NewEntities returns a new Entities instance
func NewEntities(hashtags []TextTag, mentions []TextTag, urls []Url) *Entities {
return &Entities{
Hashtags: hashtags,
Mentions: mentions,
Urls: urls,
}
}
// Validate implements fmt.Validator
func (e *Entities) Validate() error {
for _, tag := range e.Hashtags {
err := tag.Validate()
if err != nil {
return fmt.Errorf("invalid hashtag: %s", err)
}
}
for _, tag := range e.Mentions {
err := tag.Validate()
if err != nil {
return fmt.Errorf("invalid mention: %s", err)
}
}
for _, url := range e.Urls {
err := url.Validate()
if err != nil {
return fmt.Errorf("invalid url: %s", err)
}
}
// --- Make sure there are no overlapping entities based on (start, end) ---
// Map all entities into segments
segments := e.getSegments()
if len(segments) < 1 {
// We cannot have an empty entities here
return fmt.Errorf("entities must have at least one entity inside")
}
if len(segments) < 2 {
// With less than 2 segments there cannot be any overlap
return nil
}
// Sort the segments
sort.Slice(segments, func(i, j int) bool {
return segments[i].start < segments[j].start
})
// Verify there are no overlapping segments
for index := 0; index < len(segments)-1; index++ {
first, second := segments[index], segments[index+1]
if first.end >= second.start {
return fmt.Errorf("entities cannot overlap: start %d end %d", first.end, second.start)
}
}
return nil
}
// entitySegment represents an entity as a segment within a post text.
// This is used to easily determine whether there are overlapping entities specified within the post.
// Two entities are said to overlap if the end of the first is after the start of the second.
type entitySegment struct {
// start represents the index inside the post text at which this segment begins
start uint64
// end represents the index inside the post text at which this segment ends
end uint64
}
// getSegments maps all the provided Entities into segments
func (e *Entities) getSegments() []entitySegment {
segments := make([]entitySegment, len(e.Hashtags)+len(e.Mentions)+len(e.Urls))
i := 0
for _, hashtag := range e.Hashtags {
segments[i] = entitySegment{start: hashtag.Start, end: hashtag.End}
i++
}
for _, mention := range e.Mentions {
segments[i] = entitySegment{start: mention.Start, end: mention.End}
i++
}
for _, url := range e.Urls {
segments[i] = entitySegment{start: url.Start, end: url.End}
i++
}
return segments
}
// NewTextTag returns a new TextTag instance
func NewTextTag(start, end uint64, tag string) TextTag {
return TextTag{
Start: start,
End: end,
Tag: tag,
}
}
// Validate implements fmt.Validator
func (t TextTag) Validate() error {
if t.Start > t.End {
return fmt.Errorf("invalid start and end indexes: %d %d", t.Start, t.End)
}
if strings.TrimSpace(t.Tag) == "" {
return fmt.Errorf("invalid start and end indexes: %d %d", t.Start, t.End)
}
return nil
}
// NewURL returns a new Url instance
func NewURL(start, end uint64, url, displayURL string) Url {
return Url{
Start: start,
End: end,
Url: url,
DisplayUrl: displayURL,
}
}
// Validate implements fmt.Validator
func (u Url) Validate() error {
if u.Start > u.End {
return fmt.Errorf("invalid start and end indexes: %d %d", u.Start, u.End)
}
if strings.TrimSpace(u.Url) == "" {
return fmt.Errorf("invalid url value: %s", u.Url)
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// ParseAttachmentID parses the given value as an attachment id, returning an error if it's invalid
func ParseAttachmentID(value string) (uint32, error) {
if value == "" {
return 0, nil
}
attachmentID, err := strconv.ParseUint(value, 10, 32)
if err != nil {
return 0, fmt.Errorf("invalid attachment id: %s", err)
}
return uint32(attachmentID), nil
}
// Attachments represents a slice of Attachment objects
type Attachments []Attachment
// Validate implements fmt.Validators fmt.Validator
func (a Attachments) Validate() error {
ids := map[uint32]bool{}
for _, attachment := range a {
if _, ok := ids[attachment.ID]; ok {
return fmt.Errorf("duplicated attachment id: %d", attachment.ID)
}
ids[attachment.ID] = true
err := attachment.Validate()
if err != nil {
return err
}
}
return nil
}
// NewAttachment returns a new Attachment instance
func NewAttachment(subspaceID uint64, postID uint64, id uint32, content AttachmentContent) Attachment {
contentAny, err := codectypes.NewAnyWithValue(content)
if err != nil {
panic("failed to pack content to any type")
}
return Attachment{
SubspaceID: subspaceID,
PostID: postID,
ID: id,
Content: contentAny,
}
}
// Validate implements fmt.Validator
func (a Attachment) Validate() error {
if a.SubspaceID == 0 {
return fmt.Errorf("invalid subspace id: %d", a.SubspaceID)
}
if a.PostID == 0 {
return fmt.Errorf("invalid post id: %d", a.PostID)
}
if a.ID == 0 {
return fmt.Errorf("invalid attachment id: %d", a.ID)
}
if a.Content == nil {
return fmt.Errorf("invalid attachment content")
}
return a.Content.GetCachedValue().(AttachmentContent).Validate()
}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (a *Attachment) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
var content AttachmentContent
return unpacker.UnpackAny(a.Content, &content)
}
// --------------------------------------------------------------------------------------------------------------------
// AttachmentMove contains data related to a attachment that can be updated after it has been moved.
type AttachmentMove struct {
// ID of the subspace inside which the attachment should be moved
SubspaceID uint64
// ID of the post to which the attachment should be associated within the new subspace
PostID uint64
}
// NewAttachmentMove returns a new AttachmentMove instance
func NewAttachmentMove(subspaceID uint64, postID uint64) AttachmentMove {
return AttachmentMove{
SubspaceID: subspaceID,
PostID: postID,
}
}
// Update updates the fields of a moved attachment.
func (update AttachmentMove) Update(attachment Attachment) Attachment {
return Attachment{
update.SubspaceID,
update.PostID,
attachment.ID,
attachment.Content,
}
}
// --------------------------------------------------------------------------------------------------------------------
// AttachmentContent represents an attachment content
type AttachmentContent interface {
proto.Message
isAttachmentContent()
Validate() error
Equal(other interface{}) bool
}
// PackAttachments packs the given AttachmentContent instances as Any instances
func PackAttachments(attachments []AttachmentContent) ([]*codectypes.Any, error) {
if attachments == nil {
// Avoid allocating a new array
return nil, nil
}
attachmentAnys := make([]*codectypes.Any, len(attachments))
for i := range attachments {
attachmentAny, err := codectypes.NewAnyWithValue(attachments[i])
if err != nil {
return nil, err
}
attachmentAnys[i] = attachmentAny
}
return attachmentAnys, nil
}
// UnpackAttachments unpacks the given Any instances as AttachmentContent
func UnpackAttachments(cdc codectypes.AnyUnpacker, attachmentAnys []*codectypes.Any) ([]AttachmentContent, error) {
attachments := make([]AttachmentContent, len(attachmentAnys))
for i, any := range attachmentAnys {
var content AttachmentContent
err := cdc.UnpackAny(any, &content)
if err != nil {
return nil, err
}
attachments[i] = content
}
return attachments, nil
}
// --------------------------------------------------------------------------------------------------------------------
var _ AttachmentContent = &Media{}
// NewMedia returns a new Media instance
func NewMedia(uri, mimeType string) *Media {
return &Media{
Uri: uri,
MimeType: mimeType,
}
}
func (*Media) isAttachmentContent() {}
// Validate implements fmt.Validator
func (m *Media) Validate() error {
if strings.TrimSpace(m.Uri) == "" {
return fmt.Errorf("invalid uri: %s", m.Uri)
}
if strings.TrimSpace(m.MimeType) == "" {
return fmt.Errorf("invalid mime type: %s", m.MimeType)
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
var _ AttachmentContent = &Poll{}
// NewPoll returns a new Poll instance
func NewPoll(
question string,
providedAnswers []Poll_ProvidedAnswer,
endDate time.Time,
allowsMultipleAnswers bool,
allowsAnswerEdits bool,
tallyResults *PollTallyResults,
) *Poll {
return &Poll{
Question: question,
ProvidedAnswers: providedAnswers,
EndDate: endDate,
AllowsMultipleAnswers: allowsMultipleAnswers,
AllowsAnswerEdits: allowsAnswerEdits,
FinalTallyResults: tallyResults,
}
}
func (*Poll) isAttachmentContent() {}
// Validate implements fmt.Validator
func (p *Poll) Validate() error {
if strings.TrimSpace(p.Question) == "" {
return fmt.Errorf("invalid question: %s", p.Question)
}
if len(p.ProvidedAnswers) < 2 {
return fmt.Errorf("insufficient amount of provided answers: %d", len(p.ProvidedAnswers))
}
answers := map[string]bool{}
for _, answer := range p.ProvidedAnswers {
err := answer.Validate()
if err != nil {
return err
}
if _, ok := answers[answer.Text]; ok {
return fmt.Errorf("duplicated provided answer: %s", answer.Text)
}
answers[answer.Text] = true
}
if p.EndDate.IsZero() {
return fmt.Errorf("invalid end date: %s", p.EndDate)
}
if p.FinalTallyResults != nil {
err := p.FinalTallyResults.Validate()
if err != nil {
return err
}
}
return nil
}
// IsPoll tells whether the given attachment represents a poll or not
func IsPoll(attachment Attachment) bool {
_, ok := attachment.Content.GetCachedValue().(*Poll)
return ok
}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (a *Poll) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
for _, answer := range a.ProvidedAnswers {
err := answer.UnpackInterfaces(unpacker)
if err != nil {
return err
}
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// NewProvidedAnswer returns a new Poll_ProvidedAnswer instance
func NewProvidedAnswer(text string, attachments []AttachmentContent) Poll_ProvidedAnswer {
attachmentAnys, err := PackAttachments(attachments)
if err != nil {
panic(err)
}
return Poll_ProvidedAnswer{
Text: text,
Attachments: attachmentAnys,
}
}
// Validate implements fmt.Validator
func (a Poll_ProvidedAnswer) Validate() error {
if strings.TrimSpace(a.Text) == "" {
return fmt.Errorf("invalid text: %s", a.Text)
}
// Unpack the attachments
attachments := make([]AttachmentContent, len(a.Attachments))
for i, attachmentAny := range a.Attachments {
attachments[i] = attachmentAny.GetCachedValue().(AttachmentContent)
}
// Validate the attachments
for _, attachment := range attachments {
if _, isPoll := attachment.(*Poll); isPoll {
return fmt.Errorf("cannot have a poll as an attachment of a poll's provided answer")
}
if containsDuplicatedAttachments(attachments, attachment) {
return fmt.Errorf("duplicated attachment")
}
err := attachment.Validate()
if err != nil {
return err
}
}
return nil
}
// containsDuplicatedAttachments tells whether the given attachments array contains a duplicate content
func containsDuplicatedAttachments(attachments []AttachmentContent, content AttachmentContent) bool {
var found = 0
for _, attachment := range attachments {
if attachment.Equal(content) {
found++
}
}
return found > 1
}
// UnpackInterfaces implements codectypes.UnpackInterfacesMessage
func (a *Poll_ProvidedAnswer) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
for _, attachment := range a.Attachments {
var content AttachmentContent
err := unpacker.UnpackAny(attachment, &content)
if err != nil {
return err
}
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// NewUserAnswer returns a new UserAnswer instance
func NewUserAnswer(subspaceID uint64, postID uint64, pollID uint32, answersIndexes []uint32, user string) UserAnswer {
return UserAnswer{
SubspaceID: subspaceID,
PostID: postID,
PollID: pollID,
AnswersIndexes: answersIndexes,
User: user,
}
}
// Validate implements fmt.Validator
func (a UserAnswer) Validate() error {
if a.SubspaceID == 0 {
return fmt.Errorf("invalid subspace id: %d", a.SubspaceID)
}
if a.PostID == 0 {
return fmt.Errorf("invalid post id: %d", a.PostID)
}
if a.PollID == 0 {
return fmt.Errorf("invalid poll id: %d", a.PollID)
}
if len(a.AnswersIndexes) == 0 {
return fmt.Errorf("answer indexes cannot be empty")
}
indexes := map[uint32]bool{}
for _, answer := range a.AnswersIndexes {
if _, ok := indexes[answer]; ok {
return fmt.Errorf("duplicated answer index: %d", answer)
}
indexes[answer] = true
}
_, err := sdk.AccAddressFromBech32(a.User)
if err != nil {
return fmt.Errorf("invalid user address: %s", err)
}
return nil
}
// --------------------------------------------------------------------------------------------------------------------
// NewPollTallyResults returns a new PollTallyResults instance
func NewPollTallyResults(results []PollTallyResults_AnswerResult) *PollTallyResults {
return &PollTallyResults{
Results: results,
}
}
// Validate implements fmt.Validator
func (r *PollTallyResults) Validate() error {
if len(r.Results) == 0 {
return fmt.Errorf("empty answer results")
}
ids := map[uint32]bool{}
for _, answerResult := range r.Results {
if _, ok := ids[answerResult.AnswerIndex]; ok {
return fmt.Errorf("duplicated result for answer %d", answerResult.AnswerIndex)
}
ids[answerResult.AnswerIndex] = true
}
return nil
}
// NewAnswerResult returns a new PollTallyResults_AnswerResult instance
func NewAnswerResult(answerIndex uint32, votes uint64) PollTallyResults_AnswerResult {
return PollTallyResults_AnswerResult{
AnswerIndex: answerIndex,
Votes: votes,
}
}
// --------------------------------------------------------------------------------------------------------------------
// NewPostOwnerTransferRequest returns a new PostOwnerTransferRequest instance
func NewPostOwnerTransferRequest(subspaceID uint64, postID uint64, receiver string, sender string) PostOwnerTransferRequest {
return PostOwnerTransferRequest{
SubspaceID: subspaceID,
PostID: postID,
Receiver: receiver,
Sender: sender,
}
}
// Validate checks the request validity
func (request PostOwnerTransferRequest) Validate() error {
if request.SubspaceID == 0 {
return fmt.Errorf("invalid subspace id: %d", request.SubspaceID)
}
if request.PostID == 0 {
return fmt.Errorf("invalid post id: %d", request.PostID)
}
if request.Sender == request.Receiver {
return fmt.Errorf("receiver cannot be the same as sender")
}
_, err := sdk.AccAddressFromBech32(request.Sender)
if err != nil {
return fmt.Errorf("invalid sender address: %s", request.Sender)
}
_, err = sdk.AccAddressFromBech32(request.Receiver)
if err != nil {
return fmt.Errorf("invalid receiver address: %s", request.Receiver)
}
return nil
}